Reputation: 33
I'm new to twig, and I'm trying to change the value of the letter stored in a variable to the following letter. I tried something like this:
{% set i = "a" %}
{% for answer in answers %}
{{ "("~ i ~")"}} {{ answer.content }}
{% set i = i + 1 %}
<br>
{% endfor %}
The expected output would be something like:
(a) YES
(b) -1
(c) YES
I did a little research but could not find a direct way to do so. May be there is a workaround, but I'd like to know if there is a direct way to do so.
Thanks in advance for your help. Have a good day.
Upvotes: 1
Views: 736
Reputation: 3312
You cannot "increment" a letter in twig.
But you can generate a list of letters a-z and access those in your loop:
{% set letters = range('a','z') %} # generate an array of letters a-z
{% for answer in answers %}
({{ letters[loop.index0] }}) {{ answer.content }} # access letter by loop index
<br>
{% endfor %}
This works for a maximum of 26 answers.
Addendum: Maybe its an XY-Problem. Instead of doing it yourself in twig, you could also use css and let the browser do it.
ol {
list-style-type:lower-alpha;
}
<ol>
<li>answer 1</li>
<li>answer 2</li>
<li>answer 3</li>
</ol>
Upvotes: 2
Reputation: 1445
There isn't any built-in way to do this in Twig.
You could create your own Twig extension and handle this logic in it.
You should use the chr function to convert your $i
variable (as an integer) into a letter. There is the famous mapping ACSI table to help you implement the twig extension.
If you want to only use alphabet characters, you must be careful if it's possible to have more than 26 questions in your application. Otherwise, you'll display a [
or {
character.
Don't hesitate if something isn't clear :)
Upvotes: 1