简体   繁体   English

如何在Twig模板中动态导出带有资源的内联JavaScript?

[英]How to dynamically export inline javascript with assetic in twig templates?

I am trying to clean up my html output in a Symfony2 Project. 我正在尝试清理Symfony2项目中的html输出。 What really bothers me is that I dont really know how to export inline JS dynamically. 真正困扰我的是,我真的不知道如何动态导出内联JS。 For example: I need to initialise Jquery Datatables, but not on every page, most of the pages have their own specific inline js. 例如:我需要初始化Jquery Datatables,但不是在每个页面上,大多数页面都有自己的特定内联js。 Im searching for a way to just extend a twig block with my js snippets, that gets grouped together and loaded by assetic from an external (virtual) .js file. 我正在寻找一种方法来扩展带有我的js代码片段的细枝块,该片段被组合在一起并由来自外部(虚拟).js文件的素材资源加载。

Yes, you need to use template inheritance and have a parent javascript/jquery block. 是的,您需要使用模板继承并具有父javascript / jquery块。 Jquery is the same as javascript so you can include that in one block or have a seperate one. jQuery与javascript相同,因此您可以将其包含在一个块中或单独使用一个块。 If you are using a variable, then pass that variable to the base jquery section. 如果您使用的是变量,则将该变量传递给基本jquery部分。 For your different pages, you need to extend the base twig file and either add to the javascript block by including the parent or overriding it entirely. 对于您的不同页面,您需要扩展基本树枝文件,并通过包括父项或完全覆盖它来将其添加到javascript块中。

base twig file has basic html layout with js and css blocks: 基本的Twig文件具有js和CSS块的基本html布局:

<!DOCTYPE html>
<html>
    <head>
        {% block head %}
            <link rel="stylesheet" href="style.css" />
            <title>{% block title %}{% endblock %} - My Webpage</title>
        {% endblock %}
        {% block js %}
            <script src="{{ asset('js/main.js') }}"></script>
        {% endblock %}

    </head>
    <body>
        <div id="content">{% block content %}{% endblock %}</div>
        <div id="footer">
            {% block footer %}
                &copy; Copyright 2011 by <a href="http://domain.invalid/">you</a>.
            {% endblock %}
        </div>
    </body>
</html>

This is inherited by the child page 这是由子页面继承的

{% extends "base.html" %}

{% block title %}Index{% endblock %}
{% block js%}
    {{ parent() }}
    <script src="jquery.plugin.js"></script>
{% endblock %}
{% block content %}
    <h1>Index</h1>
    <p class="important">
        Welcome on my awesome homepage.
    </p>
{% endblock %}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM