Random raw value in twig

Today's small task - in the twig template, you need to randomly display one of the values, which is an image.

In the case of outputting a single value, we could use the code

{{ some_value | raw }}

however, in our case it will not work, so we find the following solution:

{% autoescape false %}
    {% set first = '<img src="/files/themes/img/1.jpg" />' %}
    {% set second = '<img src="/files/themes/img/2.jpg" />' %}
    {% set third = '<img src="/files/themes/img/3.jpg" />' %}
    {{ random([first, second, third]) }}
{% endautoescape %}

Brief explanation

{% autoescape false %}{% endautoescape %} - allows us to display values as they are, i.e. in the form of processed html code, without this entry, we will get just plain, raw text.

{% set first = '<img src="/files/themes/img/1.jpg" ðÊÉíU ðÊÉíU ЛÉÉíU  ™ÉÉíU XÊÉíU ÊÉíU @ ÊÉíU econd, third]) }} - returns a random value from the given array.

Plain text

  • No HTML tags allowed.
  • Lines and paragraphs break automatically.
  • Web page addresses and email addresses turn into links automatically.
The comment language code.