Loops

For working on recordsets or iterable data types, you need a construct to loop through lists. In the QWeb template, this can be done with the t-foreach element. Iteration can happen in a t element, in which case its contents are repeated for every member of the iterable that was passed in the t-foreach attribute, as follows:

<t t-foreach="[1, 2, 3, 4, 5]" t-as="num">
<p><t t-esc="num"/></p>
</t>

This will be rendered as follows:

<p>1</p>
<p>2</p>
<p>3</p>
<p>4</p>
<p>5</p>

You can also place the t-foreach and t-as attributes in some arbitrary element, at which point this element and its contents will be repeated for every item in the iterable. Take a look at the following code block. This will generate exactly the same result as the previous example:

<p t-foreach="[1, 2, 3, 4, 5]" t-as="num">
<t t-esc="num"/>
</p>

In our example, take a look at the inside of the t-call element, where the actual content generation happens. The template expects to be rendered with a context that has a variable called books set that iterates through it in the t-foreach element. The t-as attribute is mandatory and will be used as the name of the iterator variable, to use it for accessing the iterated data. While the most common use for this construction is to iterate over recordsets, you can use it on any Python object that is iterable.

Within t-foreach loops, you've got access to a couple of extra variables, whose names are derived from the accompanying t-as attribute. As it is book in the preceding example, we have access to the book_odd variable that contains the value True for odd indices while iterating, and False for even ones. In this example, we used this to be able to have alternating background colors in our cards.

The following are other available variables:

  • book_index, which returns the current (zero-based) index in the iteration.
  • book_first and book_last, which are True if this is the first or last iteration, respectively.
  • book_value, which would contain the item's value if the book variable we iterate over were a dictionary; in this case, book would iterate through the dictionary's keys.
  • book_size, which is the size of the collection (if available).
  • book_even and book_odd get true values, based on the iteration index.
  • book_parity contains the even value for even indices while iterating, and odd for odd ones.
The given examples are based on our example. In your case, you need to replace book with the value placed at the t-as attribute.
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset