我真的想在我的symfony 2项目中使用assetic,因为它有许多有用的功能,但我不确定实现以下要求的最佳方法.
我有几个js文件可以包含在所有页面中.但是,其中一些仅与页面模板的子集相关,其中我包含需要特定javascript文件的特定模板(或嵌入特定控制器).
现在我有以下选择:
我在布局和特定页面模板(我在其中包含带有javascript的模板,例如templateWithComplexJs.html.twig)中为javascripts创建了一个块元素,我使用{{parent()}}覆盖此块,如此处所述:跨继承模板组合资产资源.
{# ... specific.html.twig #}
{% extends 'MyBundle::layout.html.twig' %}
...
{% include 'MyBundle:Foo:templateWithComplexJs.html.twig' %}
...
{% block javascripts %}
{{ parent() }}
{% javascripts
'@MyBundle/Resources/public/js/specific/complex.js'
%}
<script src="{{ asset_url }}"></script>
{% endjavascripts %}
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
我看到的缺点:
a)当我调整包含的模板(例如更新到新的js lib)时,我必须调整所有页面模板,包括它们.在一个容易导致错误的复杂系统中.
b)可能会发生两次javascript,一次在布局中,一次在模板的javascript中,资产不知道,因为它们被单独处理.
我包含了布局中所需的所有js文件,然后我只需要在调整包含的模板时更改一个位置,并且我不太可能包含两次javascripts.
我看到的缺点是:
由于js文件的大小很大,我宁愿只在少数情况下将它们包含在我真正需要它们的时候.
在这个相关的问题(几个模板中的Twig Assetic Stylesheets)中,它表示目前无法通过资产来实现令人满意的解决方案,但我想我并不是唯一一个有这些要求并且想要使用资产的人.
那么,这种场景的最佳实践是什么?
小智 7
您可以更简单地获得您的目标.在配置文件中设置资产组并为其命名,而不是在所有模板中执行此操作.这是一个简单的例子.
# Assetic Configuration
assetic:
debug: %kernel.debug%
use_controller:
enabled: false #%kernel.debug%
profiler: false
java: /usr/bin/java
node: /usr/bin/node
assets:
backend_css:
inputs:
- %kernel.root_dir%/../path/to/some/css/file.css
- %kernel.root_dir%/../path/to/some/less/file.less
filters:
- less
output: css/backend.css
frontend_css:
inputs:
- %kernel.root_dir%/../path/to/some/css/file.css
- %kernel.root_dir%/../path/to/some/less/file.less
filters:
- less
output: css/frontend.css
backend_js:
inputs:
- %kernel.root_dir%/../path/to/some/js/file.js
- %kernel.root_dir%/../path/to/some/js/other.js
filters:
- yui_js
output: js/backend.js
frontend_js:
inputs:
- %kernel.root_dir%/../path/to/some/js/file.js
- %kernel.root_dir%/../path/to/some/js/other.js
filters:
- yui_js
output: js/frontend.js
special_backend_js:
inputs:
- %kernel.root_dir%/../path/to/some/js/file.js
- %kernel.root_dir%/../path/to/some/js/other.js
filters:
- yui_js
output: js/special_backend.js
filters:
cssrewrite: ~
cssembed:
jar: %kernel.root_dir%/Resources/java/cssembed-0.4.5.jar
# closure:
# jar: %kernel.root_dir%/Resources/java/compiler.jar
yui_css:
jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
yui_js:
jar: %kernel.root_dir%/Resources/java/yuicompressor-2.4.7.jar
less:
node_paths: [%kernel.root_dir%/Resources/node_modules]
apply_to: "\.less$"
Run Code Online (Sandbox Code Playgroud)
现在,在您的枝条模板中,您可以执行以下操作:
{% block javascript %}
<script src="{{ asset('js/backend.js') }}"></script>
{% endblock javascript %}
Run Code Online (Sandbox Code Playgroud)
并为您的css资产做同样的事情.这样,如果你想在你的backend.js集合中添加另一个库,或者包含一些js功能组,比如special_backend,它就是你模板中的一个内容,当你进行更改时,你只需要处理你的配置定义.
我希望能帮助你一点点.我确信还有其他方法可以完成这项工作,但这是我首选的方法.
| 归档时间: |
|
| 查看次数: |
1759 次 |
| 最近记录: |