我将哪些服务注入自定义块服务,以便我可以使用assetic为块特定资源(js和css)生成有效的绝对URL?我想要这样的东西:
class CustomBlockService extends Sonata\BlockBundle\Block\BaseBlockService {
protected $urlmaker;
function __construct($name, $templating, SomeService $urlmaker){
parent::__construct($name, $templating);
$this->urlmaker = $urlmaker;
}
public function getStylesheets($media)
{
return array(
$this->urlmaker('treegrid_css');
);
}
public function getJavascripts($media)
{
return array(
$this->urlmaker('treegrid_js');
);
}
//rest of class
}
我正在使用SonataBlockBundle输出一些自定义块。一些块需要javascripts(或css),这些javascripts(或css)在其他任何地方都没有使用。所以在我的基本模板中,我这样做了:
{% block javascripts %}
<!-- scripts on every page -->
{% javascripts
'@jquery_js'
'@bootstrap_js'
'@select2_js'
'@sonata_base_js'
%}
<script type="text/javascript" src="{{ asset_url }}"></script>
{% endjavascripts %}
<!-- BLOCK-SPECIFIC scripts -->
{{ sonata_block_include_javascripts('all') }}
{% endblock %}
sonata twig extension sonata_block_include_javascripts
要求自定义块服务覆盖此函数,如果它想要指定javascripts:
public function getJavascripts($media)
{
return array(
'bundles/bundlename/path/to/script.js'
);
}
我的Symfony项目已设置好,以便Bower管理的组件存在于此处:
%kernel.root.dir%/Resources/components/bower_components
,不幸的是SonataBlockBundle相对于web
输出的路径。
我有一个Assetic,assetic.yml的配置文件,它命名了我可能想要包含的每个资源。通过这样做,当我从dev切换到prod环境时,我不必与Assetic争论文件路径。除非我愿意,否则我也不必依赖与第三方软件包捆绑在一起的资源。 (例如,不同版本的jQuery,每个包一个!)
assetic.yml摘录
assets:
jquery_js:
inputs:
- '%kernel.root_dir%/Resources/components/bower_components/jquery/jquery.min.js'
jqueryui_js:
inputs:
- '%kernel.root_dir%/Resources/components/bower_components/jqueryui/ui/minified/jquery-ui.min.js'
- '%kernel.root_dir%/Resources/components/bower_components/jqueryui/ui/minified/i18n/jquery-ui-i18n.min.js'
bootstrap_js:
inputs:
- %kernel.root_dir%/Resources/components/bower_components/bootstrap/dist/js/bootstrap.min.js
treegrid_js:
inputs:
- %kernel.root_dir%/Resources/components/bower_components/treegrid/js/jquery.treegrid.js
- %kernel.root_dir%/Resources/components/bower_components/treegrid/js/jquery.treegrid.bootstrap3.js
main_css:
inputs:
- %kernel.root_dir%/Resources/components/css/main.css
filters: [cssrewrite]
treegrid_css:
inputs:
-%kernel.root_dir%/Resources/components/bower_components/treegrid/css/jquery.treegrid.css