我正在使用 Odoo 13,但这是一个 QWeb 问题:
我在QWeb中得到如下模板:
<template id="my_subtemplate">
<t t-set="foo" t-value="foo + 1"/>
<p>Inside subtemplate: <t t-esc="foo"/></p>
</template>
在其他模板中,我调用了两次,这样:
<t t-set="foo" t-value="1"/>
<t t-call="my_module.my_subtemplate"/>
<t t-call="my_module.my_subtemplate"/>
<p>Inside main template: <t t-esc="foo"/></p>
所以当我调用主模板时,我期望得到这个结果:
Inside subtemplate: 2
Inside subtemplate: 3
Inside main template: 3
但是,我得到这个:
Inside subtemplate: 2
Inside subtemplate: 2
Inside main template: 1
不能在子模板中修改变量吗?关于如何完成如此简单的任务有什么想法吗?
第一个问题:似乎在子模板中是不可能的。引自 13.0 文档:
或者,调用指令主体中设置的内容将是 在调用子模板之前评估,并且 can alter a local 上下文:
我将“本地上下文”解释为您内部
foo
的范围保留在子模板中,就像拥有外部foo
的副本。
第二题:难。你可以使用循环,比如:
<t t-set="foo" t-value="1"/>
<t t-for="your_iterable" t-as="item">
<t t-set="foo" t-value="foo + 1"/>
<t t-call="my_module.my_subtemplate"/>
<p>Inside main template: <t t-esc="foo"/></p>
<!-- subtemplate without t-set!!! -->
可以工作,因为现在
foo
一直保持在同一个范围内。