2

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?

Leon He
  • 41
  • 1
  • 2

2 Answers2

4

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] }}
robert
  • 1,402
  • 1
  • 15
  • 21
1

Are a and b your types? If so you can just use their string values directly:

template.cpp

{% for type in types %}
top -> {{type}}(var{{loop.index0}});
{% endfor %}

main.py

import jinja2
import os.path
template_dir = os.path.dirname(__file__)
jinja_env = jinja2.Environment(loader = jinja2.FileSystemLoader(template_dir),
                               autoescape = False)

t = jinja_env.get_template('template.cpp')
types = ['a', 'b', 'c']
print (t.render(types=types))

main.py output from run:

top -> a(var0);

top -> b(var1);

top -> c(var2);
cphurley82
  • 64
  • 7
  • The "types" list is actually just and indicator of how many elements to have. a, b, c, etc are not the types, but are the names of variables for a module. The types list would look something like this: types = ['uint32_t', 'char', 'float'] However, I did realize that I could just use another list which just contains all the lowercase letters so it would be {% for type in types %} top -> {{letters[loop.index0]}}(var{{loop.index0}}); {% endfor %} – Leon He Apr 10 '15 at 02:50