Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Jinja2 ASCII to String

I had this line in my Jinja2 template:

{% for type in types %}
    top -> {{(loop.index0 + 'a')|string}}(var{{loop.index0}});
{% endfor %}

where types is a list of various types in C++ that is used elsewhere in the template and the output is part of a SystemC program to initialize module signals. The goal is to get an output like this with characters starting from lowercase a:

top -> a(var0);
top -> b(var1);

However, it was giving this error: "unsupported operand type(s) for +: 'int' and 'str'" so I tried changing the template to this:

{% for type in types %}
    top -> {{(loop.index0 + 'a'|int)|string}}(var{{loop.index0}});
{% endfor %}

but then the output was this

top -> 0(var0);
top -> 1(var1);

It seems that the issue is that there is no way to convert from an integer to its corresponding ASCII character within the Jinja2 template. I tried "chr()" but that is a Python function and not a Jinja2 one and doesn't work. I was wondering if there is anyone who has had experience with this and could help me out?

like image 827
Leon He Avatar asked Mar 21 '26 08:03

Leon He


1 Answers

Answering the question posed by the title question: "Jinja2 ASCII to String"

# Returns "a" if 'my_index' is 0, "b" if 1, etc.
{{ "abcdefghijklmnopqrstuvwxyz"[my_index] }}

# Use the char_code as the index.
{{ "abcdefghijklmnopqrstuvwxyz"[char_code - 97] }}
like image 84
robert Avatar answered Mar 22 '26 21:03

robert



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!