Search code examples
phpsymfonytwigtemplatingassetic

Symfony Assetic function using with variable


<img src="{{ asset("assets/img/sample.jpg") }}"/>

i want to using sample.jpg with filter

{% image "assets/img/sample.jpg" filter="jpegoptim" %}
    <img src"{{ asset_url }}"/>
{% endimage %}

everything is all here.

but i want take file from a variable. like this:

{% set image = "sample.jpg" %}

{% image "assets/img/"~image filter="jpegoptim" %}
    <img src="{{ asset_url }}"/>
{% endimage %}

Error:

Unexpected token "name" of value "image"

if i use twig jpegoptim function with this configuration

#config.yml

assetic:
    debug:          '%kernel.debug%'
    use_controller: '%kernel.debug%'
    filters:
        jpegoptim:
            bin: /usr/bin/jpegoptim
            strip_all: true
            max: 80
    twig:
        functions:
            jpegoptim: ~

template file:

<img src="{{ jpegoptim("assets/img/"~image) }}/>

Error:

Notice: Undefined index: jpegoptim in . (which is being imported from "/var/www/html/myproject/app/cache/dev/assetic/routing.yml").

Solution

  • There is a solution end of the official page here. They say use the LiipImageBundle.

    http://symfony.com/doc/current/assetic/jpeg_optimize.html

    Url based filter sample:

    <img src="{{ asset('/relative/path/to/image.jpg') | imagine_filter('my_thumb') }}" />