t-foreach:仅在从 JS 注入 dict 列表到 XML 时呈现最后一个条目

问题描述

问题:尝试将变量值从 JS 传递到 XML 时,只有最后一个条目使用 t-foreach 指令呈现。

当前结果:只有最后一项进入 DOM

<div class="p-3 bg-light">
  <h5>ertyujbhjkl</h5>
  <p>buy cake</p>
  <p>fjkjjjjj</p>
</div>

预期:每个项目都应该呈现

<div class="p-3 bg-light">
  <h5>fsfgshsj</h5>
  <p>buy milk</p>
  <p>yuu</p>
</div>
<div class="p-3 bg-light">
  <h5>ertyujbhjkl</h5>
  <p>buy cake</p>
  <p>fjkjjjjj</p>
</div>

代码

JS

function app() {
    class TestCall extends owl.Component {
        constructor() {
            super(...arguments);
            this.items = [
                {
                    id: 3,title: "fsfgshsj",date: "buy milk",about: "yuu",},{
                    id:4,title: "ertyujbhjkl",date: "buy cake",about: "fjkjjjjj",];
        }
    }

    class App extends owl.Component { }
    App.components = { TestCall };


    //------------------------------------------------------------------------------
    // Application Startup
    //------------------------------------------------------------------------------

    owl.mount(App,{ target: document.body });

}

/**
 * Initialization code
 * This code load templates,and make sure everything is properly connected.
 */
async function start() {
    let templates;
    try {
        templates = await owl.utils.loadFile('app.xml');
        console.log('found')
    } catch (e) {
        console.error(`This app requires a static server.  If you have python installed,try 'python app.py'`);
        return;
    }
    const env = { qweb: new owl.QWeb({ templates }) };
    owl.Component.env = env;
    await owl.utils.whenReady();
    app();
}

start();

模板:

<templates>
    
    <t t-name="TestCall" t-foreach="items" t-as="item">
        <div class="p-3 bg-light" t-key="item.id">
            <h5 t-esc="item.title"></h5>
            <p t-esc="item.date"></p>
            <p t-raw="item.about"></p>
        </div>
    </t>

    <div t-name="App" class="app">
        <TestCall />
    </div>
</templates>

解决方法

a github issue中所述,

从 Owl ged-odoo 的评论来实现所需的功能:

  1. <t t-name="TestCall" ... 行改为 <div t-name="TestCall">
  2. t-foreach 移到 div 应用程序下方

生成的代码 XML 是:

    <div t-name="TestCall" >
        <div class="p-3 bg-light" t-foreach="items" t-as="item" t-key="item.id">
            <h5 t-esc="item.title"></h5>
            <p t-esc="item.date"></p>
            <p t-raw="item.about"></p>
        </div>
    </div>

好消息:Gery 承诺将从 OWL 2.0 开始支持此功能