Search code examples
xmlodooodoo-13qweb

What is the scope of the variables passed to subtemplates in QWeb?


I am using Odoo 13, but this is a QWeb question:

I got the following template in QWeb:

<template id="my_subtemplate">
    <t t-set="foo" t-value="foo + 1"/>
    <p>Inside subtemplate: <t t-esc="foo"/></p>
</template>

In other template, I call it twice, this way:

<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>

So when I call the main template, I expect to get this result:

Inside subtemplate: 2
Inside subtemplate: 3
Inside main template: 3

However, I am getting this one:

Inside subtemplate: 2
Inside subtemplate: 2
Inside main template: 1

Can't variables be modified in a subtemplate? Any ideas of how to do such a simple task?


Solution

  • To the first question: seems it's not possible in subtemplates. A quote from the 13.0 doc:

    Alternatively, content set in the body of the call directive will be evaluated before calling the sub-template, and can alter a local context:

    I interpret "local context" as the scope of your inner foo stays in the subtemplate, like having a copy of the outer foo.

    Second question: difficult. You could use loops, like:

    <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!!! -->
    

    Could work, because now foo stays in the same scope all the time.