如何在Twig过滤器中使用变量“替换” [英] How to use variables in Twig filter 'replace'

查看:165
本文介绍了如何在Twig过滤器中使用变量“替换”的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

从表格php移交数组

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

到Twig模板中,我想替换每个Twig变量中的字符串替换与此类似的过滤器:

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?

推荐答案

要么传递整个数组,要么循环替换。

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

但是在循环替换时,您需要在括号中包装 key value 来强制插入这些

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

小提琴

这篇关于如何在Twig过滤器中使用变量“替换”的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆