Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use if in Odoo template language

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

like image 733
Mariano DAngelo Avatar asked Jan 08 '23 14:01

Mariano DAngelo


2 Answers

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>
like image 199
Ludwik Trammer Avatar answered Jan 10 '23 04:01

Ludwik Trammer


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"/>
like image 36
Emipro Technologies Pvt. Ltd. Avatar answered Jan 10 '23 05:01

Emipro Technologies Pvt. Ltd.