How can I make a "for-loop" with a specific number of loops in Qweb?
Asked Answered
H

3

7

I would like to make a loop to print elements an exact amount of times. Something like this:

<t t-for="o.label_qty" >
...
</t>

Where o.label_qty is an integer number.

But I can use only a t-foreach loop in qweb:

<t t-foreach="o.pack_operation_ids" t-as="l" >
...
</t>

Is there a way to do this?

If not I'm thinking the only solution is to create a dummy list with o.label_qty elements and write it in the foreach.

Haft answered 17/7, 2015 at 12:25 Comment(0)
T
12

The t-foreach directive accepts a Python expression. So, you could use range() just like in Python for loops:

<t t-foreach="range(o.label_qty)" t-as="l">
...
</t>
Tonyatonye answered 17/7, 2015 at 22:1 Comment(2)
if o.label_qty store float value then it will raise error TypeError: range() integer end argument expected, got float. So we have do type casting from float to intParulis
For Python 3.x, I believe we have to use list(range())Laurenelaurens
D
7

yes it totally possible in Odoo Qweb Report you just need to add the below way to do somethings like this

     <t t-foreach="o.pack_operation_ids" t-as="l" >
         <td class="col-xs-1">
             <span t-esc="l_index+1"/>
         </td>
     </t>

hear the <span> tag is print the total no of times loop will be executed while we are printing our qweb report. index is the part of Qweb Template Engine so hear it is always start with 0 element.

I hope my answer may help you :)

Derick answered 17/7, 2015 at 13:40 Comment(0)
P
3

range() function will raise error for floating value.

For example:

>>>a=1.0
>>>range(a)
>>>Traceback (most recent call last):
   File "<stdin>", line 1, in <module>
   TypeError: range() integer end argument expected, got float.

For dynamic variable loops, there are two possibility for looping with specific number.

  1. Integer number (as answered by @Daniel Reis)
  2. Float number (try with following)

    <t t-set="i" t-value="int(o.label_qty)"/>
    <t t-foreach="range(i)" t-as="l">
    ...
    </t>
    

for more details of range() function.

Parulis answered 30/3, 2017 at 8:51 Comment(1)
You are right Odedra. But I specified in my question that o.label_qty is a integer number so I think the answer of Daniel Reis is enough. Thanks for your contributionHaft

© 2022 - 2024 — McMap. All rights reserved.