Symfony2 - Assetic - load images in CSS

后端 未结 9 2082
逝去的感伤
逝去的感伤 2020-11-29 17:38

I have a CoreBundle that contains main css files and images. Now I have a problem when I load an image from css; the image isn\'t shown.

 background-image:ur         


        
9条回答
  •  [愿得一人]
    2020-11-29 17:58

    I solved this using htaccess:

    My assets are stored in src/Datacode/BudgetBundle/Resources/public/(css|img|js) and the assetic output parameter is set to write to: bundles/datacodebudget/css/styles.css (in web directory)

    In my css i use the relative path ../ to reference images.

    Here is the .htaccess rule:

    # Make image path work on dev
    # i.e. /app_dev.php/bundles/datacodebudget/img/glyphicons-halflings-white.png rewrites to /bundles/datacodebudget/img/glyphicons-halflings-white.png
    RewriteRule ^app_dev\.php/(.*)/(.*)/img/(.*)$ /$1/$2/img/$3 [L]
    

    My css is loaded as follows:

    {% stylesheets
        '@DatacodeBudgetBundle/Resources/public/css/bootstrap.css'
        '@DatacodeBudgetBundle/Resources/public/css/bootstrap-responsive.css'
        '@DatacodeBudgetBundle/Resources/public/css/styles.css' 
        '@DatacodeBudgetBundle/Resources/public/css/chosen.css' output="bundles/datacodebudget/css/styles.css"
    %}
    
    {% endstylesheets %}
    

    In my config.yml file i have:

    assetic:
        use_controller: true
    

    Which (without the htaccess rewrite) causes the images not to load since the relative path for the image is at app_dev.php/bundles/datacodebudget/img/someimage.jpg. Using the cssrewrite filter doesn't work either because then it rewrites ../img to ../../../../Resources/public/img/ which resolves to Resources/public/img.

    By using the htaccess method the images load fine and I only need to run assetic:dump / assets:install when i add new images or want to push changes to production.

提交回复
热议问题