Twig:如何获取字符串中的第一个字符 [英] Twig: How to get the first character in a string

查看:35
本文介绍了Twig:如何获取字符串中的第一个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在实施按字母顺序搜索.我们显示一个名称表.我只想突出显示那些名称以相应字母开头的字母.

I am implementing an alphabetical search. We display a table of Names. I want to highlight only those alphabets, which have names that begin with the corresponding alphabet.

我被一个简单的问题难住了.

I am stumped with a simple problem.

如何读取 twig 中字符串 user.name 的第一个字符.我尝试了多种策略,包括 [0] 操作,但它会引发异常.这是代码

How to read the first character in the string user.name within twig. I have tried several strategies, including the [0] operation but it throws an exception. Here is the code

{% for i in ['a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z','0-9'] %}
       {% set has_user_starting_with_alphabet = false %}
       {% for user in pagination %}
              {% if user.name[0]|lower == i %}
                      {% set has_user_starting_with_alphabet = true %}
              {% endif %}
       {% endfor %}
       {% if has_user_starting_with_alphabet %}
              <li><a href="{{ path(app.request.get('_route'), { 'search_key' : i}) }}"><span>{{ i }}</span></a></li>
       {% endif %}
{% endfor %}

twig 中有没有类似starts_with"的函数?

Is there some function like "starts_with" in twig?

推荐答案

从 twig 1.12.2 开始,您可以使用 第一:

Since twig 1.12.2 you can use first:

{% if user.name|first|lower == i %}

对于旧版本,您可以使用 slice:

For older version you can use slice:

{% if user.name|slice(0, 1)|lower == i %}

这篇关于Twig:如何获取字符串中的第一个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆