Skip to content
Advertisement

Replace a string with array values in Twig

I searched on Google for some options to replace a string with some array values in Twig, but I couldn’t find anything useful.

Is it possible to replace a string with array values in Twig?

I tried to code something like this:

{% set foo = ['.JPG', '.BMP'] %}
{% for Item in ProductImage %}
<tr>
  <td class="lo-stats__image">
    <img class="border rounded" src="http://5.12.82.223/ftp/images/{{ brand_number }}/{{ Item.PictureName|replace('.jpg': foo) }}">
  </td>
</tr>
{% endfor %}

In clasic PHP is working this way:

$photoarray = array('JPG', 'BMP');
str_replace($photoarray,"jpg", $image);

Advertisement

Answer

The arguments of your filter call is slightly incorrect, it should be something like this:

{% if Item.PictureName ends with '.jpg' %}
    <img class="border rounded" src="http://5.12.82.223/ftp/images/{{ brand_number }}/{{ Item.PictureName|replace({'.jpg': '.JPG'}) }}">
{% endif %}

As described in the replace filter docs:

replace¶

The replace filter formats a given string by replacing the placeholders (placeholders are free-form):

{{ “I like %this% and %that%.”|replace({‘%this%’: foo, ‘%that%’: “bar”}) }}

{# outputs I like foo and bar if the foo parameter equals to the foo string. #}

{# using % as a delimiter is purely conventional and optional #}

{{ “I like this and –that–.”|replace({‘this’: foo, ‘–that–‘: “bar”}) }}

{# outputs I like foo and bar #}

Arguments¶

from: The placeholder values
User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement