“以"开头在树枝模板中

2022-01-22 00:00:00 regex comparison php twig

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

I have a twig template where I would like to test if an item begins with a certain value

{% 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 可能看起来像这样或更复杂,例如 0x0120D52000D430D2B0D8DD6F4BBB16123680E4F787006540​​36413B65C740B168E780DA0FB4BX.我唯一想做的就是确保它以 0x0120 开头.

The 0x0120 can look like that or be more complex like this 0x0120D52000D430D2B0D8DD6F4BBB16123680E4F78700654036413B65C740B168E780DA0FB4BX. The only thing I want to do is to ensure that it starts with the 0x0120.

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

The ideal solution would be to solve this by using regex but I'm not aware if Twig supports this?

谢谢

推荐答案

是的,Twig 在比较中支持正则表达式:http://twig.sensiolabs.org/doc/templates.html#comparisons

Yes, Twig supports regular expressions in comparisons: http://twig.sensiolabs.org/doc/templates.html#comparisons

在你的情况下是:

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

相关文章