我正在使用 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 文档中的引用:
Alternatively, content set in the body of the call directive will be evaluated before calling the sub-template, and can alter a local context:
我将“本地上下文”解释为内部 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
始终保持在同一范围内。
关于xml - 传递给 QWeb 子模板的变量的范围是什么?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/76055944/