[Odoo][Qweb]Dictionary foreach, print key and value

FTK picture FTK · Dec 6, 2015 · Viewed 14.5k times · Source

Is there a way to print key and value from a python dictionary in loop Qweb? For example, if I have a fuction that return a dictionary:

def get_informations(self):
    mydico={'myfirstkey':1,'mysecondkey':2}
    return mydico

And then, in Qweb report:

<t t-foreach="doc.get_informations()" t-as="l">
    <tr>
       <td class="text-right">
         <t t-esc="l"/>
       </td>
       <td class="text-right">
         <span t-esc="l_value"/>
       </td>
    </tr>
</t>

How could I print the key and the value ?

Thanks

Update 07/12/15:

Thank you for your return. Exactly, when I put

 <t t-foreach="{'my': 'first', 'my2': 'second' }" t-as="v">

It works, I have something like:

my    first
my2   second

But when I use a function in foreach, with exactly the same output, qweb can't separate it, and I have:

{'my': 'first', 'my2': 'second' }
{'my': 'first', 'my2': 'second' }

So I decided to do another way:

In my inherit report:

<t t-foreach="doc.tabTaxes" t-as="v">
    <tr>
        <td>
            <span t-esc="v.name"/>
        </td>
        <td>
            <span t-esc="doc.get_amount(v.name)[0]"/>
        </td>
    </tr>
</t>

In sale.order models inherit :

@api.one
def get_amount(self, taxeNom):
    total=0
    for ligne in self.order_line:
        for taxe in ligne.tax_id:
            if (taxeNom == taxe.name):
                try: total += ligne.price_reduce * (taxe.amount/100.)
                except: total +=0
    return "{0:.2f}".format(total)

Answer

ifixthat picture ifixthat · Dec 7, 2015

@FTK,

Given that your function is returning valid dictionary to qWeb template, the below code should do the job :

    <div id="wrap" class="oe_structure">
        <t t-foreach="{'my': 'first', 'my2': 'second' }" t-as="v">
         *<t t-esc="v"/> : <t t-esc="v_value"/></t>
    </div> 

And you can put tr in loop so it will create table row as you expect, code below will do that way :

    <div id="wrap" class="oe_structure">
        <table class="table table-bordered table-condensed">
            <t t-foreach="doc.get_informations()" t-as="item">
                <tr>
                    <td class="text-right">
                        <t t-esc="item"/>
                    </td>
                    <td class="text-right">
                        <t t-esc="item_value"/>
                    </td>
                </tr>
            </t>
        </table>
    </div>

you certainly don't need div their as required. Hope this will help you,

Bests,