Question

I searched a lot but could not find a solution to achieve this:

{% for i in 1..6 %}
   <li>
      {% image '@MyBundle/Resources/public/images/college/demo/facilities/thumbs/laboratory/'~i~'.jpg' %}
      <img class="facThumb" src="{{ asset_url }}" alt="Facilitiy"/>
      {% endimage %}
   </li>
{% endfor %}

Name of the images should be dynamic. Please help.

The above code throws error:

Unexpected token "operator" of value "~"

Solution:

According to what @Nic posted (accepted answer), the only workaround seems to be this:

{% for i in 1..6 %}
    <li>
        <img src="{{ asset('bundles/digicreekil/images/college/demo/facilities/thumbs/laboratory/t'~i~'.jpg') }}" alt='demo'/>
    </li>
{% endfor %}
Was it helpful?

Solution

You can't use variables in Assetic (and therefore in the {% image %} tag). The reason is, according to Kris Wallsmith (creator of Assetic):

(...) that Assetic needs to be able to parse a Twig template and extract any assets that are defined there. This is not possible if you use a variable in the tag.

Christophe Coevoet adds:

The assets are dumped when using the CLI command for this, not when rendering the page. So you cannot use variables as you don't have their values.

See this GitHub issue for the complete conversation.

Remember that Assetic creates and optimizes the assets when you run app/console assetic:dump, not when the page is actually rendered. Therefore, it cannot know of any values, it can only work with static assets.

So if you want to work with dynamic assets, you'll have to do something like this:

{% for i in 1..6 %}
   <li>
      <img class="facThumb" src="{{ asset('images/college/demo/facilities/thumbs/laboratory/'~i~'.jpg') }}" alt="Facilitiy"/>
   </li>
{% endfor %}

In this case, you can iterate through the numbers 1-6 and use the variable in the asset's URL because you're not using Assetic, but Twig's asset() function. asset() simply returns the full URL of the asset, it doesn't do any optimizations so it can be executed during runtime.

But if you want to use Assetic's optimizations and filters, you can also give it the static assets:

<li>
    {% image '@MyBundle/Resources/public/images/college/demo/facilities/thumbs/laboratory/1.jpg' %}
    <img class="facThumb" src="{{ asset_url }}" alt="Facilitiy"/>
    {% endimage %}
</li>
<li>
    {% image '@MyBundle/Resources/public/images/college/demo/facilities/thumbs/laboratory/2.jpg' %}
    <img class="facThumb" src="{{ asset_url }}" alt="Facilitiy"/>
    {% endimage %}
</li>
<li>
    {% image '@MyBundle/Resources/public/images/college/demo/facilities/thumbs/laboratory/3.jpg' %}
    <img class="facThumb" src="{{ asset_url }}" alt="Facilitiy"/>
    {% endimage %}
</li>

(etc.)

This way, you'll have to copy the same code 6 times, but it allows you to use Assetic.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top