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

16,943

Solution 1

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>

Solution 2

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 :)

Solution 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.

Share:
16,943
ChesuCR
Author by

ChesuCR

I have worked with Python, XML, Bootstrap, Odoo Framework, PostgreSQL, Bokeh Library (Python), Electron (Nodejs), Arduino and more. I am a developer who enjoys learning and helping. Contact me in LinkedIn or GitHub.

Updated on June 13, 2022

Comments

  • ChesuCR
    ChesuCR almost 2 years

    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.

  • Bhavesh Odedra
    Bhavesh Odedra about 7 years
    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 int
  • ChesuCR
    ChesuCR about 7 years
    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 contribution
  • Vinh VO
    Vinh VO about 6 years
    For Python 3.x, I believe we have to use list(range())