MaximeBernard
MaximeBernard

Reputation: 1100

Override an image from a bundle

I have this:

ShopBundle
  Controller
  Resources
    public
      images
        marker.png
    views
      Default
        index.html.twig

In my index.html.twig, I'd like to have this

<img src="{{ asset("images/marker.png") }}"/>

And I'd love people using my bundle who just want to use their own marker.png to just have to build a bundle inheriting mine and place their image just by following files structure:

MyShopBundle
  Resources
    public
      images
        marker.png

Is there any simple way to do this in Symfony2 ? The need seems so simple that I can't believe I didn't find answers already.

So,

Upvotes: 5

Views: 2989

Answers (1)

Nicolai Fr&#246;hlich
Nicolai Fr&#246;hlich

Reputation: 52513

Solution:

use the @ syntax ...

{% image '@VendorMyShopBundleBundle/Resources/public/images/example.jpg'
    output='/images/example.jpg' %}
    <img src="{{ asset_url }}" alt="Example"/>
{% endimage %}

Please note that Vendor/YourBundle/Resources/public will NOT be accessible by your web server normally.

The assets:install command will therefore copy the assets to web/bundles/vendoryourbundle

The {{ asset('path/to/asset.jpg') }} function will adjust the url of your asset if youre using the dev environment:

 http://hostname/app_dev.php 

from

/path/to/asset.jpg 

to

/app_dev.php/to/asset.jpg

[EDIT]

if you want more control over the assets maybe consider using asset collections.

You can configure them as follows:

# app/Resources/config/config.yml

assetic:
    [...]
    assets:
        css_bootstrap:
            inputs:
                -  %kernel.root_dir%/../src/Vendor/YourBundle/Resources/public/twitter-bootstrap/less/bootstrap.less
                - [...]
            filters:
                - lessphp
                - [...]
            output: css/bootstrap.css

         my_image:
            inputs: 
                - %kernel.root_dir%/../path/to/image.png
            filters:
                - optipng
            output: images/image-with-new-name.png

and use them afterwards in your template like this:

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

I am NOT sure right now if the assetic/assets/packagename/inputs configuration array supports the @VendorYourBundle syntax aswell and then uses bundle inheritance though.

Addition:

Before you can use these packages you will have to use the console command:

php app/console assetic:dump

Upvotes: 6

Related Questions