Twig read image height/width attributes

7.2k Views Asked by At

I have an image like so:

{% image output='/images/foo.jpg' '@MyBundle/Resources/public/images/bar.jpg' %}
    <img src="{{ asset(asset_url) }}" alt="Something">
{% endimage %}

now I would like to get the image dimensions and add width and height attributes like

{% image output='/images/foo.jpg' '@MyBundle/Resources/public/images/bar.jpg' %}
    <img src="{{ asset(asset_url) }}" alt="Something" width="{{ asset(asset_width) }}" height="{{ asset(asset_height) }}">
{% endimage %}

Is this possible?

Best Regards

1

There are 1 best solutions below

3
On

In your controller, do

return $this->render(
    'assetic'  => array(
        'vars'  => array(
            'height'  => '300px',
            'width'  => '400px'
        )
);

Then in your twig template

{% image vars=['height', 'width'] output='/images/foo.jpg?{height}x{width}' '@MyBundle/Resources/public/images/bar.jpg' %}
    <img src="{{ asset(asset_url) }}" alt="Something" height="{{assetic.vars.height}}" width="{{assetic.vars.width}}">
{% endimage %}

The only limitation/problem with this approach is, you need to include the dynamic variables (height and width) in the output url.

Do let us know how it went

Regards,