Twig: How to get the first character in a string
Asked Answered
P

3

29

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.

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 %}

Is there some function like "starts_with" in twig?

Prevail answered 25/1, 2012 at 6:58 Comment(0)
D
59

Since twig 1.12.2 you can use first:

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

For older version you can use slice:

{% if user.name|slice(0, 1)|lower == i %}
Dipietro answered 25/1, 2012 at 7:2 Comment(0)
D
8

Note: You may also use this notation:

{% if user.name[:1]|lower == i %}

Dortch answered 21/8, 2014 at 17:56 Comment(2)
Doesn't answer the question.Confectioner
He asks how to get the first letter of a string. user.name[:1] does exacly that.Dortch
E
0

You could also make the code a lot simpler, probably:

{% set character = user.name|first|lower %}

{% if character in 'abcdefghijklmnopqrstuvwxyz0123456789' %}
   <li><a href="{{ path(app.request.get('_route'), { 'search_key' : character}) }}"><span>{{ character }}</span></a></li>
{% endif %}

Or depending on the use case:

<li><a href="{{ path(app.request.get('_route'), { 'search_key' : user.name|first|lower}) }}"><span>{{ user.name|first|lower }}</span></a></li>
Epanodos answered 12/2 at 11:37 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.