安装AsseticBundle
在symfony2.8以上默认没有安装Assetic这个静态资源管理工具,需要通过composer来安装。
cd到项目根目录,执行:
composer require symfony/assetic-bundle
然后在app/AppKernel.php注册AsseticBundle:
$bundles = array( [...] new Symfony\Bundle\AsseticBundle\AsseticBundle(), [...] );
最后在app/config/config.yml中添加如下信息:
assetic: debug: "%kernel.debug%" use_controller: false filters: cssrewrite: ~
如果没有安装Assetic,就在twig中使用Assetic的语法,会提示未知tag
cssrewrite是将css中的有关图片的路径进行重写。
为Twig引入css/js/image
1.引入一个目录下所有的css:
{% block stylesheets %} {% stylesheets 'bundles/bossindex/css/*' %} <link ref="stylesheet" href="{{ asset_url }}" > {% endstylesheets %} {% endblock %}
上面的会将web/bundles/bossindex/css/下所有的文件以<link ref="stylesheet" href="{{ asset_url }}" >的形式循环写入html文件中。
2.引入某些css文件
{% block stylesheets %} {% stylesheets 'bundles/bossindex/css/amazeui.min.css' 'bundles/bossindex/css/admin.css' filter='cssrewrite' %} <link ref="stylesheet" href="{{ asset_url }}" > {% endstylesheets %} {% endblock %}
上面是一种写法,推荐使用这种写法,这种写法可以保证cssrewrite成功执行。也可以使用@bossIndexBundle的方式(但这种方式无法使用cssrewrite):
{% block stylesheets %} {% stylesheets '@bossIndexBundle/Resources/public/css/amazeui.min.css' '@bossIndexBundle/Resources/public/css/admin.css' %} <link ref="stylesheet" href="{{ asset_url }}" > {% endstylesheets %} {% endblock %}
3.最直接的方式:
{% block stylesheets %} <link ref="stylesheet" href="{{ asset('@bossIndexBundle/Resources/public/css/amazeui.min.css') }}" > <link ref="stylesheet" href="{{ asset('bundles/bossindex/css/admin.css') }}" > {% endblock %}
这种写法适合使用在引入image的时候使用。
注意点:
- 1. css、js、image等资源文件最好放在所在Bundle的Resources/public下。当然也可以放在/web/bundles下。
- 2. 可以使用终端命令 php app/console assetic:dump 查看当前assetic管理的资源文件
- 3. 当将资源放在对应Bundle下后,如果在页面没有加载资源文件,可能需要手动将资源文件安装到web/bundles,执行:php app/console assets:install web
引入js和image的方式和上面差不多,简单示例:
{% block javascripts %} {% javascripts '@bossIndexBundle/Resources/public/js/amazeui.ie8polyfill.min.js' '@bossIndexBundle/Resources/public/js/amazeui.min.js' '@bossIndexBundle/Resources/public/js/app.js' %} <script src="{{ asset_url }}"></script> {% endjavascripts %} {% endblock %}
引入图片:
{% block image_ico %} <link rel="icon" type="image/png" href="{{ asset('bundles/bossindex/i/favicon.png') }}" > <link rel="apple-touch-icon-precomposed" href="{{ asset('bundles/bossindex/i/app-icon72x72@2x.png') }}"> {% endblock %}
参考:
http://symfony.cn/docs/cookbook/assetic/asset_management.html
Comments | NOTHING