PHPFixing
  • Privacy Policy
  • TOS
  • Ask Question
  • Contact Us
  • Home
  • PHP
  • Programming
  • SQL Injection
  • Web3.0

Tuesday, January 18, 2022

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

 January 18, 2022     symfony, templates, twig, web     No comments   

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
  • Share This:  
  •  Facebook
  •  Twitter
  •  Stumble
  •  Digg
Newer Post Older Post Home

0 Comments:

Post a Comment

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

Total Pageviews

Featured Post

Why Learn PHP Programming

Why Learn PHP Programming A widely-used open source scripting language PHP is one of the most popular programming languages in the world. It...

Subscribe To

Posts
Atom
Posts
Comments
Atom
Comments

Copyright © PHPFixing