Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Override an image from a bundle

Tags:

symfony

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,

  • How do you include an image asset in your bundle template from your bundle resources directory ? I already did a ./apps/hfr/console assets:install web but my template does not print the right url (/images/marker.png instead of /bundles/ShopBundle/Resources/public/images/png)

  • Is it possible to override the way I want or did I lost my way ?

like image 421
MaximeBernard Avatar asked May 21 '13 14:05

MaximeBernard


1 Answers

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
like image 199
Nicolai Fröhlich Avatar answered Oct 29 '22 02:10

Nicolai Fröhlich