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?

drmind
  • 83
  • 1
  • 1
  • 4
  • 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 May 04 '17 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 May 05 '17 at 17:34
  • Seems I found it, output with {% autoescape false %} ... {% endautoescape %} – drmind May 05 '17 at 17:51

1 Answers1

12

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

DarkBee
  • 16,592
  • 6
  • 46
  • 58