【问题标题】:how to use php string function in twig template engine如何在树枝模板引擎中使用php字符串函数
【发布时间】:2012-02-10 10:50:54
【问题描述】:

我想在 twig 中使用几个 php 字符串函数。例如

如何在twing中编写下面的代码?

if (!empty($message) && substr_count($message, 'blabla')) {
   ....
   ....
}

【问题讨论】:

    标签: php django-templates template-engine twig


    【解决方案1】:

    你不能,这就是 twig 的全部意义所在。 模板应该只负责显示数据。

    在这种特定情况下,您可以创建一个 TWIG 变量,并简单地传递 TRUE 或 FALSE,这样您的 twig 代码将如下所示:

    {% if display_message %}
    ...
    {% enfif %}
    

    您可以查看 twig 模板中可用的表达式列表,strstr_count 不是其中的一部分:(http://twig.sensiolabs.org/doc/templates.html#expressions

    【讨论】:

      【解决方案2】:

      使用过滤器:

      {% if message is not empty and ... %}
       ...
      {% endif %}
      

      我认为 twig 没有等效的 substr_count,您可以进行测试并将结果传递给模板,或者创建一个 twig 扩展并自己实现它

      http://twig.sensiolabs.org/documentation

      【讨论】:

        猜你喜欢
        • 2015-03-21
        • 1970-01-01
        • 1970-01-01
        • 2013-08-07
        • 1970-01-01
        • 2012-01-11
        • 2012-07-27
        • 2018-05-24
        • 2011-12-03
        相关资源
        最近更新 更多