Макет

In this chapter, you will learn how to:

  • Create a custom header.

  • Create a custom footer.

  • Modify a standard template.

  • Add a copyright section.

  • Improve your website’s responsiveness.

За замовчуванням

An Odoo page combines cross-page and unique elements. Cross-page elements are the same on every page, while unique elements are only related to a specific page. By default, a page has two cross-page elements, the header and the footer, and a unique main element that contains the specific content of that page.

<div id="wrapwrap">
   <header/>
      <main>
         <div id="wrap" class="oe_structure">
            <!-- Page Content -->
         </div>
      </main>
   <footer/>
</div>

Any Odoo XML file starts with encoding specifications. After that, you must write your code inside an <odoo> tag.

<?xml version="1.0" encoding="utf-8" ?>
<odoo>
   ...
</odoo>

Примітка

Using precise template names is important to find information through all modules quickly. Template names should only contain lowercase alphanumerics and underscores.

Always add an empty line at the end of your file. This can be done automatically by configuring your IDE.

XPath

XPath (XML Path Language) is an expression language that enables you to navigate through elements and attributes in an XML document easily. XPath is used to extend standard Odoo templates.

A view is coded the following way.

<template id="..." inherit_id="..." name="...">
   <!-- Content -->
</template>

Атрибут

Опис

id

ID of the modified view

inherited_id

ID of the standard view (using the following pattern: module.template)

name

Human-readable name of the modified view

For each XPath, you modify two attributes: expression and position.

Example

/website_airproof/views/website_templates.xml
<template id="layout" inherit_id="website.layout" name="Welcome Message">
   <xpath expr="//header" position="before">
      <!-- Content -->
   </xpath>
</template>

This XPath adds a welcome message right before the page content.

Попередження

Be careful when replacing default elements“ attributes. As your theme extends the default one, your changes will take priority over any future Odoo update.

Примітка

  • You should update your module every time you create a new template or record.

  • XML IDs of inheriting views should use the same ID as the original record. It helps to find all inheritance at a glance. As final XML IDs are prefixed by the module that creates them, there is no overlap.

Expressions

XPath uses path expressions to select nodes in an XML document. Selectors are used inside the expression to target the right element. The most useful ones are listed below.

Descendent selectors

Опис

/

Вибирає з кореневого вузла.

//

Вибирає вузли в документі з поточного вузла, який відповідає виділенню, незалежно від їхнього розташування.

Селектори атрибутів

Опис

*

Вибирає будь-який тег XML. * можна замінити певним тегом, якщо вибір потрібно зробити точнішим.

*[@id=»id»]

Вибирає певний ID.

*[hasclass(«class»)]

Вибирає певний клас.

*[@name=»name»]

Вибирає тег із певною назвою.

*[@t-call=»t-call»]

Вибирає певний t-call.

Позиція

Позиція визначає, де розміщується код у шаблоні. Можливі значення наведено нижче:

Позиція

Опис

replace

Замінює цільовий вузол вмістом XPath.

inside

Додає вміст XPath всередину цільового вузла.

before

Додає вміст XPath перед цільовим вузлом.

after

Додає вміст XPath після цільового вузла.

атрибути

Додає вміст XPath всередині атрибута.

Example

Цей XPath видаляє перший елемент за допомогою класу .breadcrumb.

<xpath expr="//*[hasclass('breadcrumb')]" position="replace"/>

Цей XPath додає додатковий елемент <li> після останнього дочірнього елемента <ul>.

<xpath expr="//ul" position="inside">
   <li>Last element of the list</li>
</xpath>

Цей XPath додає <div> перед <nav>, який є прямим дочірнім елементом <header>.

<xpath expr="//header/nav" position="before">
   <div>Some content before the header</div>
</xpath>

Цей XPath видаляє x_airproof_header з атрибута class заголовка. У цьому випадку вам не потрібно використовувати атрибут separator.

<xpath expr="//header" position="attributes">
   <attribute name="class" remove="x_airproof_header" />
</xpath>

Цей XPath додає x_airproof_header до атрибута class заголовка. Вам також потрібно визначити атрибут separator, щоб додати пробіл перед класом, який ви додаєте.

<xpath expr="//header" position="attributes">
   <attribute name="class" add="x_airproof_header" separator=" "/>
</xpath>
Цей XPath переміщує елемент з класом .o_footer_scrolltop_wrapper перед елементом з

Атрибут ID footer.

<xpath expr="//div[@id='footer']" position="before">
   <xpath expr="//div[@id='o_footer_scrolltop_wrapper']" position="move" />
</xpath>

Порада

Використання директив move всередині іншого XPath змушує вас використовувати лише цей тип директив.

Example

Гарний приклад:
<xpath expr="//*[hasclass('o_wsale_products_main_row')]" position="before">
<xpath expr="//t[@t-if='opt_wsale_categories_top']" position="move" />
</xpath>
<xpath expr="//*[hasclass('o_wsale_products_main_row')]" position="before">
<div><!-- Content --></div>
</xpath>
Поганий приклад:
<xpath expr="//*[hasclass('o_wsale_products_main_row')]" position="before">
<xpath expr="//t[@t-if='opt_wsale_categories_top']" position="move" />
<div><!-- Content --></div>
</xpath>

Перегляньте також

Більше інформації про XPath можна знайти в цій шпаргалца.

QWeb

QWeb – це основний механізм шаблонів, який використовується Odoo. Це механізм шаблонів XML, який використовується переважно для створення фрагментів та сторінок HTML.

Перегляньте також

Документація шаблонів QWeb.

Користувацькі поля

Залежно від ваших потреб, ви можете створювати власні поля для збереження даних у базі даних.

Декларація

Спочатку створіть запис для оголошення поля. Це поле має бути пов’язане з існуючою моделлю.

/website_airproof/data/fields.xml
<record id="x_post_category" model="ir.model.fields">
   <field name="name">x_post_category</field>
   <field name="field_description">...</field>
   <field name="ttype">html</field>
   <field name="state">manual</field>
   <field name="index">0</field>
   <field name="model_id" ref="website_blog.model_blog_post"/>
</record>

Примітка

Створення полів також можливе (і рекомендується) через модель з використанням Python.

Back-end

Додайте поле до відповідного представлення за допомогою XPath. Таким чином, користувач зможе побачити поле в інтерфейсі та заповнити його пізніше.

/website_airproof/views/backend/website_blog_views.xml
<record id="view_blog_post_form_category" model="ir.ui.view">
   <field name="name">view_blog_post_form_category</field>
   <field name="model">blog.post</field>
   <field name="inherit_id" ref="website_blog.view_blog_post_form"/>
   <field name="arch" type="xml">
      <xpath expr="//field[@name='blog_id']" position="before">
         <field name="x_post_category" string="..." placeholder="..."/>
      </xpath>
   </field>
</record>

Front-end

Значення поля можна відобразити десь на сторінці, викликавши model_name.field_name ось так:

/website_airproof/views/website_blog_templates.xml
<h1 t-field="blog_post.x_post_category"/>

Фон

Ви можете визначити колір або зображення як фон вашого веб-сайту.

Кольори

/website_airproof/static/src/scss/primary_variables.scss
$o-color-palettes: map-merge($o-color-palettes,
   (
      'airproof': (
         'o-cc1-bg':                     'o-color-5',
         'o-cc5-bg':                     'o-color-1',
      ),
    )
);

Зображення/візерунок

/website_airproof/static/src/scss/primary_variables.scss
$o-website-values-palettes: (
   (
      'body-image': '/website_airproof/static/src/img/background-lines.svg',
      'body-image-type': 'image' or 'pattern'
   )
);

Standard

Конструктор веб-сайтів Odoo розрізняє шаблони для комп’ютерів та мобільні шаблони, щоб полегшити адаптацію користувацького досвіду відповідно до пристрою.

Шаблон для робочого столу

Увімкніть один із шаблонів заголовків за замовчуванням.

Важливо

Не забувайте, що вам може знадобитися спочатку вимкнути шаблон активного заголовка.

Example

/website_aiproof/data/presets.xml
<record id="website.template_header_default" model="ir.ui.view">
   <field name="active" eval="False"/>
</record>

Явно вкажіть потрібний шаблон у файлі primary_variables.scss.

/website_airproof/static/src/scss/primary_variables.scss
$o-website-values-palettes: (
   (
      'header-template': 'Contact',
   ),
);
/website_airproof/data/presets.xml
<record id="website.template_header_contact" model="ir.ui.view">
   <field name="active" eval="True"/>
</record>

Шаблон мобільного пристрою

Кожен шаблон заголовка постачається з шаблоном template_header_mobile, що забезпечує безперебійну взаємодію з користувачем на всіх пристроях.

Користувацький

Створіть власний шаблон і додайте його до списку.

Важливо

Не забувайте, що вам може знадобитися спочатку вимкнути активний шаблон заголовка, перш ніж увімкнути користувацький.

Параметр

Використайте наступний код, щоб додати параметр для вашого нового власного заголовка в Конструкторі веб-сайтів.

/website_airproof/views/website_templates.xml
<template id="template_header_opt" inherit_id="website.snippet_options" name="Header Template - Option">
   <xpath expr="//we-select[@data-variable='header-template']" position="inside">
      <we-button title="airproof"
         data-customize-website-views="website_airproof.header"
         data-customize-website-variable="'airproof'"  data-img="/website_airproof/static/src/img/wbuilder/template_header_opt.svg"/>
   </xpath>
</template>

Атрибут

Опис

data-customize-website-views

Шаблон для увімкнення

data-customize-website-variable

Назваа, надана змінній

data-img

Мініатюра власного шаблону, що відображається у виборі шаблонів у Конструкторі веб-сайтів

Тепер вам потрібно чітко визначити, що ви хочете використовувати свій власний шаблон у змінних Odoo SASS.

/website_airproof/static/src/scss/primary_variables.scss
$o-website-values-palettes: (
   (
      'header-template': 'airproof',
   ),
);

Шаблон

/website_airproof/views/website_templates.xml
<template id="header" inherit_id="website.layout" name="Airproof - Header" active="True">
   <xpath expr="//header//nav" position="replace">
      <!-- Static Content -->
      <!-- Components -->
      <!-- Editable areas -->
   </xpath>
</template>

Не забудьте відповідно адаптувати template_header_mobile, щоб зберегти узгодженість між настільними та мобільними версіями:

website_airproof/views/website_templates.xml
<template id="template_header_mobile" inherit_id="website.template_header_mobile" name="Airproof - Template Header Mobile">
   <!-- Xpaths -->
</template>

Компоненти

У вашому користувацькому заголовку ви можете викликати кілька підшаблонів за допомогою директиви t-call з QWeb:

Увійти

<t t-call="portal.placeholder_user_sign_in">
   <t t-set="_item_class" t-valuef="nav-item"/>
   <t t-set="_link_class" t-valuef="nav-link"/>
</t>

Випадаючий список користувача

<t t-call="portal.user_dropdown">
   <t t-set="_user_name" t-value="true"/>
   <t t-set="_icon" t-value="false"/>
   <t t-set="_avatar" t-value="false"/>
   <t t-set="_item_class" t-valuef="nav-item dropdown"/>
   <t t-set="_link_class" t-valuef="nav-link"/>
   <t t-set="_dropdown_menu_class" t-valuef="..."/>
</t>

Вибір мови

<t t-call="website.placeholder_header_language_selector">
   <t t-set="_div_classes" t-valuef="..."/>
</t>

Заклик до дії

<t t-call="website.placeholder_header_call_to_action">
   <t t-set="_div_classes" t-valuef="..."/>
</t>

Drop zone

Замість того, щоб визначати повний макет сторінки, ви можете створювати будівельні блоки (фрагменти) та дозволяти користувачеві вибирати, куди їх перетягувати, створюючи макет сторінки самостійно. Ми називаємо це модульним дизайном.

Ви можете визначити порожню область, яку користувач зможе заповнити фрагментами.

<div id="oe_structure_layout_01" class="oe_structure"/>

Клас

Опис

oe_structure

Визначте область перетягування для користувача.

oe_structure_solo

У цій області можна розмістити лише один фрагмент.

oe_structure_not_nearest

Якщо будівельний блок скинуто за межі зони скидання цього класу, блок буде переміщено до найближчої зони скидання.

Ви також можете заповнити наявну зону скидання своїм вмістом.

<template id="oe_structure_layout_01" inherit_id="..." name="...">
   <xpath expr="//*[@id='oe_structure_layout_01']" position="replace">
      <div id="oe_structure_layout_01" class="oe_structure oe_structure_solo">
         <!-- Content -->
      </div>
   </xpath>
</template>

Адаптивний

Odoo загалом спирається на фреймворк Bootstrap, який спрощує адаптацію вашого вебсайту до…

комп’ютер та мобільний пристрій. На Odoo 16 ви можете вживати заходів переважно у 3 аспектах:

  1. Автоматично обчислювані розміри шрифтів залежно від пристрою

  2. Розміри стовпців на комп’ютері (стовпці автоматично складаються в один ряд на мобільному пристрої)

  3. Умови видимості (показати/приховати щось на комп’ютері/мобільному пристрої)

Розміри шрифтів

У Bootstrap 5 адаптивні розміри шрифтів увімкнено за замовчуванням, що дозволяє тексту масштабуватися природніше в різних розмірах пристроїв та областей перегляду (залежить від змінної $enable-rfs).

Розміри стовпців

Bootstrap uses a grid made of rows and columns to layout a page. Thanks to this structure, columns can be sized differently on mobile and desktop. In this version, the Website Builder allows to set mobile sizes (col-12 for example) and desktop ones (col-lg-4 for example) but not the medium breakpoints (col-md-4 for example).

Попередження

The medium sizes can be set but the end-user is not able to edit them within the Website Builder.

Visibility conditions

In the Odoo Website Builder, entire sections or specific columns can be hidden on mobile or desktop.

This functionality leverages Bootstrap along with Odoo-specific classes:

  • o_snippet_mobile_invisible

  • o_snippet_desktop_invisible

Hide a section on desktop:

<section class="s_text_block o_cc o_cc1 o_colored_level pt16 pb16 d-lg-none o_snippet_desktop_invisible" data-snippet="s_text_block" name="Text">
    <!-- Content -->
</section>

Hide a column on mobile:

<section class="s_text_block o_cc o_cc1 o_colored_level pt16 pb16" data-snippet="s_text_block" name="Text">
   <div class="container s_allow_columns">
      <div class="row">
         <div class="col-12 col-lg-6 d-none d-lg-block o_snippet_mobile_invisible">
            Column 1
         </div>
         <div class="col-12 col-lg-6">
            Column 2
         </div>
      </div>
   </div>
</section>

Клас

Опис

o_snippet_mobile_invisible

It tells the Website Builder that the element is hidden and is using visibility conditions option.

o_snippet_desktop_invisible

It tells the Website Builder that the element is hidden on desktop and is using visibility conditions option.

d-none

Hide the element in every situations.

d-lg-block

Show the element from the «large» breakpoint (on desktop).

Важливо

o_snippet_mobile_invisible / o_snippet_desktop_invisible classes have to be specified to keep

the visibility conditions option functional. Even if an element is hidden on desktop, the Website Builder displays a list of these elements allowing the end-user to force show the element and edit it without switching between mobile and desktop mode.

Force show a hidden element on the current device.