我正在实施按字母顺序搜索.我们显示一个名称表.我想只突出显示那些名称以相应字母开头的字母表.
我很难过一个简单的问题.
如何读取twig中字符串user.name中的第一个字符.我已经尝试了几种策略,包括[0]操作,但它会引发异常.这是代码
{% 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 %}
Run Code Online (Sandbox Code Playgroud)
在树枝上有一些像"starts_with"这样的功能吗?
mez*_*eze 38
从twig 1.12.2开始,您可以使用first:
{% if user.name|first|lower == i %}
Run Code Online (Sandbox Code Playgroud)
对于旧版本,您可以使用slice:
{% if user.name|slice(0, 1)|lower == i %}
Run Code Online (Sandbox Code Playgroud)
注意:您也可以使用此表示法:
{% if user.name[:1]|lower == i %}
| 归档时间: |
|
| 查看次数: |
22719 次 |
| 最近记录: |