2

我的 Jinja2 模板中有这一行:

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

其中 types 是模板中其他地方使用的 C++ 中各种类型的列表,输出是 SystemC 程序的一部分,用于初始化模块信号。目标是获得这样的输出,其中字符从小写 a 开始:

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

但是,它给出了这个错误:“+ 的不支持的操作数类型:'int'和'str'”所以我尝试将模板更改为:

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

但后来的输出是这样的

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

似乎问题在于没有办法在 Jinja2 模板中将整数转换为其对应的 ASCII 字符。我尝试了“chr()”,但这是一个 Python 函数,而不是 Jinja2 函数,并且不起作用。我想知道是否有人有这方面的经验并可以帮助我?

4

2 回答 2

4

回答标题问题提出的问题:“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] }}
于 2016-03-31T20:22:22.760 回答
1

a 和 b 是你的类型吗?如果是这样,您可以直接使用它们的字符串值:

模板.cpp

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

主文件

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 输出:

top -> a(var0);

top -> b(var1);

top -> c(var2);
于 2015-04-09T21:02:49.813 回答