Tuesday, January 18, 2022

[FIXED] How to increment the value of a string variable with one character on twig?

Issue

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.


Solution

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>



Answered By - simon.ro

No comments:

Post a Comment

Note: Only a member of this blog may post a comment.