Skip to Content
Odoo Меню
  • Увійти
  • Спробуйте це безкоштовно
  • Додатки
    Фінанси
    • Бухоблік
    • Виставлення рахунку
    • Витрати
    • Електронні таблиці (BI)
    • Документи
    • Підпис
    Продажі
    • CRM
    • Продажі
    • POS Магазин
    • POS Ресторан
    • Підписки
    • Оренда
    Веб-сайти
    • Конструктор веб-сайту
    • Електронна комерція
    • Блог
    • Форум
    • Живий чат
    • Електронне навчання
    Ланцюг поставок
    • Склад
    • Виробництво
    • PLM
    • Купівлі
    • Технічне обслуговування
    • Якість
    Кадри
    • Співробітники
    • Рекрутинг
    • Відпустки
    • Оцінювання
    • Рекомендації
    • Автотранспорт
    Маркетинг
    • Маркетинг соцмереж
    • Email-маркетинг
    • SMS-маркетинг
    • Події
    • Автом. маркетингу
    • Опитування
    Послуги
    • Проект
    • Табелі
    • Виїзне обслуговування
    • Служба підтримки
    • Планування
    • Призначення
    Продуктивність
    • Обговорення
    • Схвалення
    • IoT
    • IP-телефонія
    • База знань
    • WhatsApp
    Сторонні модулі Odoo Studio Платформа Odoo Cloud
  • Сфери
    Роздрібна торгівля
    • Книжковий магазин
    • Магазин одягу
    • Магазин меблів
    • Продуктовий магазин
    • Магазин будівельних матеріалів
    • Магазин іграшок
    Food & Hospitality
    • Бар та паб
    • Ресторан
    • Фастфуд
    • Guest House
    • Дистриб'ютор напоїв
    • Hotel
    Нерухомість
    • Real Estate Agency
    • Архітектурна фірма
    • Будівництво
    • Управління нерухомістю
    • Садівництво
    • Асоціація власників нерухомості
    Консалтинг
    • Бухгалтерська компанія
    • Партнер Odoo
    • Агенція маркетингу
    • Юридична фірма
    • Придбання Талантів
    • Аудит та сертифікація
    Виробництво
    • Textile
    • Metal
    • Меблі
    • Їжа
    • Brewery
    • Корпоративні подарунки
    Здоров'я & Фітнес
    • Спортивний клуб
    • Оптика
    • Фітнес-центр
    • Практики здоров'я
    • Аптека
    • Салон краси
    Trades
    • Ремонтник
    • IT-обладнання та Підтримка
    • Системи сонячної енергії
    • Shoe Maker
    • Cleaning Services
    • HVAC Services
    Інші
    • Nonprofit Organization
    • Екологічна агенція
    • Оренда білбордів
    • Фотографія
    • Лізинг велосипедів
    • Реселлер програмного забезпечення
    Browse all Industries
  • Спільнота
    Навчання
    • Навчальний посібник
    • Документація
    • Сертифікації
    • Тренування
    • Блог
    • Подкаст
    Сприяйте Освіті
    • Програма навчання
    • Бізнес гра Scale Up!
    • Відвідайте Odoo
    Отримайте програмне забезпечення
    • Завантаження
    • Порівняйте версії
    • Релізи
    Співпрацюйте
    • Github
    • Форум
    • Події
    • Переклади
    • Стати партнером
    • Services for Partners
    • Зареєструйте вашу бухгалтерську фірму
    Отримайте послуги
    • Знайдіть партнера
    • Знайдіть бухгалтера
    • Зустріньтеся з консультантом
    • Послуги з впровадження
    • Референси клієнтів
    • Підтримка
    • Оновлення
    Github Youtube Twitter Linkedin Instagram Facebook Spotify
    +1 (650) 691-3277
    Отримати демо
  • Ціни
  • Допомога

Odoo is the world's easiest all-in-one management software.
It includes hundreds of business apps:

  • CRM
  • e-Commerce
  • Бухоблік
  • Склад
  • PoS
  • Проект
  • MRP
All apps
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Вам необхідно зареєструватися, щоб взаємодіяти зі спільнотою.
All Posts Люди Значки
Мітки (View all)
odoo accounting v14 pos v15
Про цей форум
Допомога

Odoo qweb dynamic html generation

Підписатися

Отримуйте сповіщення про активність щодо цієї публікації

Це запитання позначене
xmlqwebreporting8.0
15 Відповіді
16032 Переглядів
Аватар
Paul Catinean

Hello everyone

I wanted to know how does one handle a dynamically generated xml code that is invalid before being proccessed 

For example generating a table that displays the information in two cells per row:

<t t-foreach="list" t-as="item">

    <tr t-if="item_even">

        <td><span t-field="item"></td>

    </tr t-if="item_odds>

</t>

This will not work since it's invalid xml because the closing tag has a property and neither will <t t-if="condition"> </tr> </t> since the closing tag is embeded in what the xml sees another tag

Alternatives to this would be looping over grouped items, two by two or how many you want per column, and placing them inside one <tr> in one loop but it's not that elegant

Any way around this?

3
Аватар
Відмінити
Paul Catinean
Автор

That is the purpose of the var_last var_first and var_odds var_even (in your case i_last, i_first) to hold index information see: http://odoo-80.readthedocs.org/en/latest/reference/qweb.html#loops The logic of achieving this is not the problem it's just that it does not work in qweb.You need two in the same to make a two columned table. This means you have to open on even and close on odds so the end result is 1 2

Yenthe Van Ginneken (Mainframe Monkey)

Hmm I see I understood your question wrong so I've deleted my reply as it wasn't of any value then. I'm not sure about this though, interesting question. Upvoted it :)

Yenthe Van Ginneken (Mainframe Monkey)

Have a look at this by the way: http://odoo-80.readthedocs.org/en/latest/reference/qweb.html#attributes

Paul Catinean
Автор

My theory (though could very well be wrong) is that the error comes in even before qweb can kick into action.If qweb would come in and resolve the t-tags and loops it would result in valid xml code But before the qweb is parsed it's actually read as standard xml where it sees a closing tag having a attribute which is invalid syntax and stops dead.It does not know that the attribute is actually a qweb condition that will output a empty closing tag which will in the end compose valid XML

Leonardo Donelli

IMO looping on a grouped list it's the correct way and a lot more elegant than a conditional closing tag.

Sajin Aziz

is this what you are trying for (last answer) , it works in qweb reports.

Аватар
Leonardo Donelli
Найкраща відповідь

You say:

Alternatives to this would be looping over grouped items, two by two or how many you want per column, and placing them inside one <tr> in one loop but it's not that elegant

But I don't think that's true at all. Conceptually, it better represents what you are trying to do, while the conditional closing tag feels more like an hack.

Also notice that your code would not generate valid XML if the number of items is odd (it would never close the last <tr> tag), and generally that's the problem with what you wanted to do: you cannot be sure that the generated html will be valid after evaluation because it depends on the context.

To create a grouped list with groups of size n:

[ l[i:i+n] for i in xrange(0, len(l), n) ]

Examples:  

 l = range(7)
>>> [ l[i:i+2] for i in xrange(0, len(l), 2) ]
[[0, 1], [2, 3], [4, 5], [6]]
>>> [ l[i:i+3] for i in xrange(0, len(l), 3) ]
[[0, 1, 2], [3, 4, 5], [6]]
>>> [ l[i:i+4] for i in xrange(0, len(l), 4) ]
[[0, 1, 2, 3], [4, 5, 6]]

1
Аватар
Відмінити
Paul Catinean
Автор

While indeed it is a limitation you cannot do conditional closing tags your explanation makes a lot of sense and it is the proper/better method of tackling this issue regardless of the templating system.Thank you for your complete and eloquent answer!

Аватар
Sajin Aziz
Найкраща відповідь

try This :

 <tr>
            <t t-foreach="list" t-as="item">

                    <td><span t-esc="item_index"/></td>
                    <t t-if="item_odd">
                        &lt;/tr &gt;
                        &lt;tr &gt;
                    </t>
            </t>

</tr>

5
Аватар
Відмінити
Paul Catinean
Автор

Sajin indeed this solution works and provides the possibility of doing conditional closing tags i.e parsing xml that would otherwise be invalid.Thank you for your help!

Mersed Kahrimanovic

Actually this is the only and complete solution on the question above. I can confirm that it works now as well. Grouping is indeed better in some of the solutions - but somtimes - grouping is bad idea as well. Consider the "one data source" for the lets say select field. If you want to implement behaviour based on the data source - and present that select field as well on the frontend, then its much easier to have one object instead grouped one.

Аватар
Hardikgiri Goswami
Найкраща відповідь

Hello Paul,

As I observed you theory is on opposite way of qweb tag (specially for the ending tag).

But I can understand what kind of output you want.

You need to create list of list.

I am explaining by your example

<t t-foreach="list" t-as="item">

    <tr t-if="item_even">

        <td><span t-field="item"></td>

    </tr t-if="item_odds>

</t>

Here "list" is a list something like [1,2,3,4,5].
and it will print like 
1
2
3
4
5

and you want it like
1   2
3   4
5

If you want something like this, then you need to pass list of list like,
your "list" should be like [[1,2],[3,4],[5]] instead of [1,2,3,4,5].
Now you xml code should be something like.

<t t-foreach="list" t-as="row">

    <tr>
        <t t-foreach="row" t-as="item">

            <td><span t-field="item"></td>
        </t>
    </tr>

</t>

and python code for converting simple "list" this "list of list" is

Option 1 :


your_list = [1,2,3,4,5,6,1,2,3,4,5,6]
new_list = []
for i in range(0, len(your_list), 2):
    temp_list = [your_list[i]]
    if i < len(your_list)-1:
        temp_list.append(your_list[i+1])
    new_list.append(temp_list)
print new_list

Option 2 :

your_list = [1,2,3,4,5,6,1,2,3,4,5,6]
new_list1 = zip(*[iter(your_list)]*2)
print new_list1

4
Аватар
Відмінити
Paul Catinean
Автор

Indeed Hardikgiri that is the alternative when looping through a grouped set

Hardikgiri Goswami

As per my knowledge solution for this question is not possible. I have tried two other ways but I got the error and stuck over there.

Аватар
Aldennis
Найкраща відповідь

I have a similar requirement but with three columns for a pay slip report. 

The solution that I came up with is to construct some part of the Qweb report in python and save the generated html in a text field.


Call the text field in the Qweb report like this:

<div t-field="o.field_name" t-options="{'widget':'html'}"/>


When the Qweb report gets generated, the content of the text field is rendered together with the rest of the report. I use this approach in Odoo13 but I guess will work on previous versions as well.

0
Аватар
Відмінити
Enjoying the discussion? Don't just read, join in!

Create an account today to enjoy exclusive features and engage with our awesome community!

Реєстрація
Related Posts Відповіді Переглядів Дія
Replace stock inventory report
stock xml qweb reporting
Аватар
0
лист. 15
4058
How can I display all tasks (including completed ones) in a QWeb report in Odoo?
qweb reporting
Аватар
Аватар
2
вер. 24
3067
t-att-href url get error Вирішено
xml qweb
Аватар
Аватар
2
квіт. 23
9711
odoo report columns not displaying
xml qweb layout reporting css
Аватар
0
бер. 23
3319
v15: object has no attribute 'generate_report'
xml reporting
Аватар
0
трав. 22
2874
Спільнота
  • Навчальний посібник
  • Документація
  • Форум
Open Source
  • Завантаження
  • Github
  • Runbot
  • Переклади
Послуги
  • Хостинг Odoo.sh
  • Підтримка
  • Оновлення
  • Кастомні доробки
  • Навчання
  • Знайдіть бухгалтера
  • Знайдіть партнера
  • Стати партнером
Про нас
  • Наша компанія
  • Торгові активи
  • Зв'яжіться з нами
  • Вакансії
  • Події
  • Подкаст
  • Блог
  • Клієнти
  • Юридичні документи • Конфіденційність
  • Безпека
الْعَرَبيّة Català 简体中文 繁體中文 (台灣) Čeština Dansk Nederlands English Suomi Français Deutsch हिंदी Bahasa Indonesia Italiano 日本語 한국어 (KR) Lietuvių kalba Język polski Português (BR) română русский язык Slovenský jazyk slovenščina Español (América Latina) Español ภาษาไทย Türkçe українська Tiếng Việt

Odoo - це набір програм для роботи з відкритим кодом, які охоплюють всі ваші потреби компанії: CRM, електронна комерція, бухгалтерський облік, склад, точка продажу, управління проектами тощо.

Унікальна пропозиція Odoo - це одночасно дуже проста у використанні та повністю інтегрована.

Website made with

Odoo Experience on YouTube

1. Use the live chat to ask your questions.
2. The operator answers within a few minutes.

Live support on Youtube
Watch now