8

Handing over an array from php of form

$repl_arr = array('serach-string1' => 'replace1', ...) 

to a Twig template I would like to replace strings in a Twig variable per replace filter similar to this:

{{ block | replace({ repl_arr }) }}

That does not function and neither a variable loop like

{% for key,item in repla_arr %}
  {% set var = block | replace({ key : item }) %}
{% endfor %}

does. What is wrong with it? How could it work?

3
  • Can you give me an example (just a good example) of what your block variable looks like and then I should have a solution.
    – Alvin Bunk
    Commented May 4, 2017 at 23:41
  • The answer of DarkBee excellently described the usage of replace filter with a hash (array). @alvin-bunk The second point indeed is the variable 'block'. It is a render array (I didn't have that in mind). So replace doesn't work with it. And when I do {% set output %} {{ block }} {% endset %} {{ output | replace(replaces) }} then html characters are escaped like e.g. <
    – drmind
    Commented May 5, 2017 at 17:34
  • Seems I found it, output with {% autoescape false %} ... {% endautoescape %}
    – drmind
    Commented May 5, 2017 at 17:51

1 Answer 1

11

Either you pass the whole array, or you loop the replaces.

But when looping the replaces you need to wrap key and value in parentheses to force interpolation of those

{% set replaces = {
    '{site}'     : '{stackoverflow}',
    '{date}'  : "NOW"|date('d-m-Y'),
} %}

{% set haystack = '{site} foobar {site} {date} bar' %}


{{ haystack | replace(replaces) }}

{% set output = haystack %}
{% for key, value in replaces %}
    {% set output = output|replace({(key) : (value),}) %}
{% endfor %} 
{{ output }}

fiddle

1
  • Did you create this answer with ChatGPT? Commented Jan 4 at 9:29

Not the answer you're looking for? Browse other questions tagged or ask your own question.