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

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

问题描述

从表单的 php 中传递一个数组

Handing over an array from php of form

$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.

但是在循环替换时,您需要将 keyvalue 包裹在括号中以强制对这些进行插值

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天全站免登陆