jinja2在模板表达式中使用数字表达式

发布于 2025-01-30 01:25:37 字数 578 浏览 2 评论 0原文

我需要做一些显然很简单的事情:

typedef enum {
    {% for e in mylist %}
    {{ e }} = 0x{{ '%04X' % (1 << loop.index0) }},
    {%- endfor %}
    ALL = 0x0FFF
} Sound_Region_t;

但是,这是用“ jinja2.exceptions.templatesyntaxerror:意外的”'''''''的炸弹,“

意图是得到类似的东西:

typedef enum {
    foo = 0x0001,
    bar = 0x0002,
    fie = 0x0004,
    fom = 0x0008,
    ...,
    ALL = 0x0FFF
} Sound_Region_t;

ie:value是一个“步行位”,所以我可以”或“可以” doplise或“可以”一起。他们。 同样的行为,如果我尝试使用其他变体,包括“ {with bit = 1&lt;&lt; loop.index%}”或类似的行为。

我想念什么?

I need to do something apparently very simple:

typedef enum {
    {% for e in mylist %}
    {{ e }} = 0x{{ '%04X' % (1 << loop.index0) }},
    {%- endfor %}
    ALL = 0x0FFF
} Sound_Region_t;

but this bombs with "jinja2.exceptions.TemplateSyntaxError: unexpected '<'"

Intention is to get something like:

typedef enum {
    foo = 0x0001,
    bar = 0x0002,
    fie = 0x0004,
    fom = 0x0008,
    ...,
    ALL = 0x0FFF
} Sound_Region_t;

I.e.: value is a "walking bit" so I can "bitwise or" together them.
Same behavior if I try to use other variations including "{% with bit = 1 << loop.index %}" or similar.

What am I missing?

如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

挖鼻大婶 2025-02-06 01:25:37

jinja2不允许模板内的位运算符,因此我们需要创建一个较小的全局函数来执行此类操作员并返回一个数字:

def leftshift(amount):
    return 1 << amount

# Get or create a Jinja2 environment
from jinja2 import Environment
env = Environment(...)

# Add leftshift function to the global context
env.globals['leftshift'] = leftshift

在模板中,现在我们可以使用loop Index:

typedef enum {
    {% for e in mylist %}
    {{ e }} = 0x{{ '{:04X}'.format(leftshift(loop.index0))}},
    {%- endfor %}
    ALL = 0x0FFF
} Sound_Region_t;

Jinja2 does not allow bitwise operators inside the templates, so we need to create a small global function that executes such operators and returns a number:

def leftshift(amount):
    return 1 << amount

# Get or create a Jinja2 environment
from jinja2 import Environment
env = Environment(...)

# Add leftshift function to the global context
env.globals['leftshift'] = leftshift

And in the templates now we can call leftshift function with the loop index:

typedef enum {
    {% for e in mylist %}
    {{ e }} = 0x{{ '{:04X}'.format(leftshift(loop.index0))}},
    {%- endfor %}
    ALL = 0x0FFF
} Sound_Region_t;
~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文