首先,我知道逻辑应该在控制器中而不是在视图中,我保持这种方式。
但在这种特殊情况下,我需要在三元操作中使用 preg_match 来设置 div 的 css 类。
例子:
{% for list in lists %}
<div class="{{ (preg_match(list.a, b))>0 ? something : else }}"...>...</div>
{% endfor %}
如何在树枝中实现(preg_match(list.a,b))>0条件?
提前致谢
您不能preg_match()直接使用,但有一些方法可以完成它:
如果您list是实体,请添加一个方法matches():{{ (list.matches(b)) ? something : else }}
preg_match()您可以创建一个内部使用的自定义 Twig 扩展函数http://symfony.com/doc/master/cookbook/templating/twig_extension.html
从 Serge 的评论中扩展,是正确的答案。
在我的示例中,我的字符串是“Message Taken - 12456756”。然后我可以使用 |split 将其转换为数组并使用 |replace 来消除空白。
{% set mt = 'Message Taken' in d.note %}
{% if mt == true %}
{#.. you can then do something that is true#}
{% set mt_array = d.note|split('-') %}
{{ mt_array[0] }} | {{ mt_array[1]|replace({' ' : ''}) }}
{% endif %}
这将输出我的字符串,但我现在控制两个部分而不是 1。