You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Odoo 16.0 QWeb模板中动态添加类或样式

Odoo QWeb模板中根据布尔字段动态添加CSS类的正确写法

我有多个布尔字段,想要在Odoo的QWeb模板里根据字段值动态添加CSS类。参考相关文档后尝试了几种写法,但都没得到预期效果:

尝试的代码:

<t t-foreach="planes" t-as="plan">
    <p t-attf-class="{{plan.blog ? 'text-success' : 'text-danger'}}">Blog</p>
    <p t-attf-class="{plan.blog ? 'text-success' : 'text-danger'}">Blog</p>
    <p t-attf-class="plan.blog ? 'text-success' : 'text-danger'">Blog</p>
    <p t-attf-class="plan.blog ? text-success : text-danger">Blog</p>
</t>

期望的渲染结果:

<p class="text-success">Blog</p>
<p class="text-danger">Blog</p>

正确的两种写法:

方法一:使用t-att-class指令

t-att-class是QWeb专门用于动态绑定class属性的指令,直接传入表达式即可:

<t t-foreach="planes" t-as="plan">
    <p t-att-class="plan.blog ? 'text-success' : 'text-danger'">Blog</p>
</t>

方法二:使用t-attf-class的字符串插值

t-attf-class支持字符串格式化,需要用{{ }}包裹表达式,让QWeb解析逻辑:

<t t-foreach="planes" t-as="plan">
    <p t-attf-class="{{ plan.blog ? 'text-success' : 'text-danger' }}">Blog</p>
</t>

之前写法的问题说明:

  • 第二个写法用了单大括号{},QWeb无法识别这种语法,必须用双大括号{{ }}
  • 第三个写法没有包裹表达式,t-attf-class会把整个表达式当成普通字符串输出
  • 第四个写法没有给类名加引号,QWeb会把text-success当成变量而非字符串常量

内容的提问来源于stack exchange,提问作者Jhordy Said Barrera

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.07.09 04:02:43