【问题标题】:preg_match in twig树枝中的 preg_match
【发布时间】:2013-02-08 09:36:39
【问题描述】:

首先,我知道逻辑应该在控制器中而不是在视图中,我保持这种方式。

但在这种特殊情况下,我需要在三元运算中使用 preg_match 来设置 div 的 css 类。

例子:

{% for list in lists %}
    <div class="{{ (preg_match(list.a, b))>0 ? something : else }}"...>...</div>
{% endfor %}

如何在 twig 中实现 (preg_match(list.a,b))>0 条件?

提前致谢

【问题讨论】:

标签: php twig


【解决方案1】:

你不能直接使用preg_match(),但是有办法实现它:

  1. 如果你的list是一个实体,添加一个方法matches(){{ (list.matches(b)) ? something : else }}

  2. 您可以创建一个自定义 Twig 扩展函数,该函数在内部使用 preg_match() http://symfony.com/doc/master/cookbook/templating/twig_extension.html

【讨论】:

    【解决方案2】:

    对于那些从 Google 搜索结果来到这里的人(比如我)。

    containment operator 允许您执行以下操作:

    {{ 'cd' in 'abcde' }} {# returns true #}

    【讨论】:

      【解决方案3】:

      根据 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。

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2022-01-02
        • 1970-01-01
        • 2015-04-22
        • 2011-06-24
        • 1970-01-01
        • 2013-05-27
        • 2012-07-27
        • 1970-01-01
        相关资源
        最近更新 更多