如何使用 Symfony2 将 JavaScript 文件包含到 twig 模板中
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/32170795/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to include JavaScript files into twig template using Symfony2
提问by gamofe
I can easily include CSS files into my twig template like this:
我可以像这样轻松地将 CSS 文件包含到我的树枝模板中:
{% block stylesheets %}
<link rel="stylesheet" href="{{ asset('bundles/user/css/bootstrap.min.css') }}"/>
<link rel="stylesheet" href="{{ asset('bundles/user/css/bootstrap-theme.min.css') }}"/>
<link rel="stylesheet" href="{{ asset('bundles/user/css/main.css') }}"/>
{% endblock %}
But for my JavaScript files
但是对于我的 JavaScript 文件
{% block javascripts %}
<script src="{{ asset('bundles/user/js/jquery-1.11.3.min.js') }}"></script>
<script src="{{ asset('bundles/user/js/bootstrap.min.js') }}"></script>
{% endblock %}
The approach does not work. I tried to use assetics
too, but that didn't work either.
该方法不起作用。我也尝试使用assetics
,但这也不起作用。
回答by lxg
I'd recommend the Assetic approach. It's not exactly simple, but it gives you huge benefits.
我会推荐 Assetic 方法。这并不完全简单,但它为您带来了巨大的好处。
First, embed your JS in a template like this:
首先,将您的 JS 嵌入到这样的模板中:
{% block my_javascripts %}
{% javascripts
'@FooBarBundle/Resources/public/js/foo.js'
'@FooBarBundle/Resources/public/js/bar.js'
filter='?uglifyjs2'
%}
<script src="{{ asset_url }}" type="text/javascript"></script>
{% endjavascripts %}
{% endblock %}
Add as many JS files as you like.
添加任意数量的 JS 文件。
Now run the following on the command line:
现在在命令行上运行以下命令:
app/console assetic:dump
In your dev
environment, this will generate a copy of your JS files within the document root. In your prod
, this will generate onecombined file in the doc root – the first benefit.
在您的dev
环境中,这将在文档根目录中生成 JS 文件的副本。在你的prod
, 这将在 doc root 中生成一个组合文件 - 第一个好处。
To have your files generated automatically in the background while you edit them, run the following from the command line, and keep it running until you're done (cancel then with Ctrl+C):
要在编辑文件时在后台自动生成文件,请从命令行运行以下命令,并保持运行直到完成(然后使用 取消Ctrl+C):
app/console assetic:watch --force
(The --force
option causes Assetic to generate the files even if it there don't seem to be any modifications.)
(--force
即使似乎没有任何修改,该选项也会导致 Assetic 生成文件。)
Another benefit is the filter='uglifyjs2'
statement: It causes the files to be "compressed" with UgilifyJS, which loads much faster.
另一个好处是filter='uglifyjs2'
声明:它使文件被 UgilifyJS“压缩”,加载速度更快。
Read more about using Assetic for JS and CSS in Symfony2 in the cookbook.