How to use if in Odoo template language

不打扰是莪最后的温柔 提交于 2019-12-07 07:05:29

问题


I'm trying to use the same functionality as in Django:

<div class="item {% if condition == True %}active{% endif %}">

In Odoo I have:

<t t-foreach="list" t-as="l">
    <a t-attf-href="/downloads/{{l.id}}" class="list-group-item"><t t-esc="l.name"/></a>
</t>

And I need to append class "active" if "c.id = cat_id"

how it's done in Odoo?

I'm using:

<t t-foreach="categories" t-as="c">
    <t t-if="c.id == category_id">
    <a t-attf-href="/downloads/{{c.id}}" class="list-group-item active"><t t-esc="c.name"/></a>
    </t>
    <t t-if="c.id != category_id">
    <a t-attf-href="/downloads/{{c.id}}" class="list-group-item"><t t-esc="c.name"/></a>
    </t>
</t>

But searching for a more pythonic way


回答1:


I don't think QWeb templates are even intended to be Pythonic ;)

You can do this if you want:

<a t-attf-href="/downloads/{{c.id}}" t-attf-class="list-group-item {{ 'active' if c.id == category_id else '' }}">
    <t t-esc="c.name"/>
</a>



回答2:


Try following,

Prepare one function in widget to compare both value and set css style to new property of that widget.

init: function(parent,options){
        //define 1 property to access this in template and set it from calling function
        this.style = '';
        this._super(parent,options);
    }
    get_comparison_result : function(cid,category_id){
        var style = "";
        if (cid != category_id){
            //Add style here
            style = "background-color:white";
        }
        else{
            //Add style here
            style = "background-color:green";
        }
        this.style = style;
        return true;
    }

Then you can call this from template and assign result to variable and use this result.

<t t-if="widget.get_comparison_result(c.id, category_id)">
    <t t-set="style" t-value="widget.style" />
</t>

<a t-attf-href="/downloads/{{c.id}}" t-att-style="style"><t t-esc="c.name"/>


来源:https://stackoverflow.com/questions/32492575/how-to-use-if-in-odoo-template-language

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!