dongzhi2332 2012-11-24 16:56
浏览 49
已采纳

Symfony 2.1 - 加载资产的问题和资产引发的异常

This is a bit frustrating. According to Symfony best practices, a bundle's web assets (images, css, js) should be placed in src/vendor/path/to/bundle/Resources/public. Running app/console assets:install copies the contents of that public folder to web/bundles/bundlename. In the official documentation, Twig templates are shown to grab these assets with code like:

{% block stylesheets %}
    <link rel="stylesheet" type="text/css" href="{{ asset('/css/styles.css') }}
{% endblock %}

When I try it, instead of magically grabbing my assets from web/bundles/bundlename/css/styles.css, it instead just goes for web/css/styles.css. Is this expected behavior? The official documentation is less than clear about this.

In order to try to combat this issue, I tried embracing assetic's ability to dynamically serve assets. I tried:

{% stylesheets '@mybundle/Resources/public/css/*' %}
    <link rel="stylesheet" type="text/css" href="{{ asset_url }}" />
{% endstylesheets %}

But got the following exception:

An exception has been thrown during the compilation of a template ("You must add mybundle to the assetic.bundle config to use the {% stylesheets %} tag in mybundle:Home:index.html.twig.") in "/home/kevin/www/src/mybundle/Resources/views/Home/index.html.twig

The official Symfony documentation makes it appear that it should work out of the box with no configuration necessary.

So, TLDR:

  1. Am I not understanding how assets should be loaded?
  2. How do I address the assetic exception?
  • 写回答

1条回答 默认 最新

  • dounei9043 2012-11-27 12:57
    关注

    To fix the assetic exception you need to configure your bundle in your config.yml like this:

    assetic:
        bundles: [ MyAwesomeBundle ]
    

    The {{ asset(...) }} twig function will serve files relative from your web root.

    You use app/console assets:install to install static assets within your web root and you can later easily point to them using the asset function like this {{ asset('/mybundle/css/site.css') }}

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 BP神经网络控制倒立摆
  • ¥20 要这个数学建模编程的代码 并且能完整允许出来结果 完整的过程和数据的结果
  • ¥15 html5+css和javascript有人可以帮吗?图片要怎么插入代码里面啊
  • ¥30 Unity接入微信SDK 无法开启摄像头
  • ¥20 有偿 写代码 要用特定的软件anaconda 里的jvpyter 用python3写
  • ¥20 cad图纸,chx-3六轴码垛机器人
  • ¥15 移动摄像头专网需要解vlan
  • ¥20 access多表提取相同字段数据并合并
  • ¥20 基于MSP430f5529的MPU6050驱动,求出欧拉角
  • ¥20 Java-Oj-桌布的计算