用 Twig 中的数组值替换字符串

Replace a string with array values in Twig

我在 Google 上搜索了一些用 Twig 中的一些数组值替换字符串的选项,但我找不到任何有用的东西。

是否可以在 Twig 中用数组值替换字符串?

我试着编写这样的代码:

{% 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 %}

在经典中 PHP 是这样工作的:

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

你的过滤器调用的参数有点不正确,应该是这样的:

{% 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 %}

如替换过滤器中所述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