Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use variables in Twig filter 'replace'

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?

like image 697
drmind Avatar asked May 04 '17 23:05

drmind


People also ask

How do you set a variable in Twig template?

This can be accomplished by creating an array of the entry years. Inside the loop that's building the array, a conditional checks if the year already exists in the array... if the year exists, a variable is set to TRUE which you can use in your conditional later down on the page. Save this answer.

How do you use a Twig filter?

Variables in Twig can be modified with help of twig filters. Filters are simply separated from variables by a pipe symbol ( | ). For applying twig filter we only need to apply the ( | ) followed by filter name. Twig comes with many filters built into it, and Drupal has a variety of filters native to it.


1 Answers

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

like image 139
DarkBee Avatar answered Oct 23 '22 07:10

DarkBee