Twig 模板中的“开头为”

问题描述 投票:0回答:4

我有一个树枝模板,我想在其中测试某个项目是否以某个值开头

{% if item.ContentTypeId == '0x0120' %}
    <td><a href='?parentId={{ item.Id }}'>{{ item.BaseName }}</a><br /></td>
{% else %}
    <td><a href='?{{ item.UrlPrefix }}'>{{ item.LinkFilename }}</a></td>
{% endif %}

0x0120 可以看起来像这样,或者更复杂,比如 0x0120D52000D430D2B0D8DD6F4BBB16123680E4F78700654036413B65C740B168E780DA0FB4BX。我唯一想做的就是确保它以 0x0120 开头。

理想的解决方案是使用正则表达式来解决这个问题,但我不知道 Twig 是否支持这个?

谢谢

php regex twig comparison
4个回答
150
投票

您现在可以直接在 Twig 中执行此操作:

{% if 'World' starts with 'F' %}
{% endif %}

还支持“结尾为”:

{% if 'Hello' ends with 'n' %}
{% endif %}

还存在其他方便的关键字:

复杂的字符串比较:

{% if phone matches '{^[\\d\\.]+$}' %} {% endif %}

(注:双反斜杠被twig转换为一个反斜杠)

字符串包含:

{{ 'cd' in 'abcde' }}
{{ 1 in [1, 2, 3] }}

33
投票

是的,Twig 支持正则表达式进行比较:https://twig.symfony.com/doc/3.x/templates.html#comparisons

在你的情况下是:

{% if item.ContentTypeId matches '/^0x0120.*/' %}
  ...
{% else %}
  ...
{% endif %}

8
投票

您可以只使用

slice
过滤器。只需做:

{% if item.ContentTypeId[:6] == '0x0120' %}
{% endif %}

1
投票

您始终可以创建自己的过滤器来执行必要的比较。

根据文档

当被 Twig 调用时,PHP 可调用函数接收过滤器的左侧(在管道 | 之前)作为第一个参数,并将额外的参数作为额外参数传递给过滤器(在括号 () 内)。

这是一个修改后的示例。

创建过滤器就像将名称与 PHP 相关联一样简单 可调用:

// an anonymous function
$filter = new Twig_SimpleFilter('compareBeginning', function ($longString, $startsWith) {
    /* do your work here */
});

然后,将过滤器添加到您的 Twig 环境中:

$twig = new Twig_Environment($loader);
$twig->addFilter($filter);

以下是如何在模板中使用它:

{% if item.ContentTypeId | compareBeginning('0x0120') == true %}
{# not sure of the precedence of | and == above, may need parentheses #}

我不是 PHP 人员,所以我不知道 PHP 如何处理正则表达式,但是上面的匿名函数被设计为如果

$longString
$startsWith
开头则返回 true。我相信您会发现实施起来很简单。

© www.soinside.com 2019 - 2024. All rights reserved.