Enable Dark Mode!
how-to-create-website-snippets-using-owl-components-in-odoo-17.jpg
By: Swaraj R

How to Create Website Snippets Using OWL Components in Odoo 17

Technical Odoo 17 Owl

In Odoo 17, snippets help you make your website more flexible by allowing you to add and update reusable components easily. With OWL (Odoo Web Library), these snippets have become more interactive and faster, using modern JavaScript tools. In this guide, we’ll show you how to create a simple partner snippet in Odoo 17 with OWL. This snippet will display a list of partners with their name, email, phone number, and address.

By the time you finish this guide, you'll have a working snippet that pulls partner information from the backend and displays it dynamically on your website.

Prerequisites

Before we code up the module, make sure you have a few things ready:

  • Odoo 17 is installed and running.
  • A basic understanding of Odoo module development.
  • Some familiarity with JavaScript, OWL, and XML.
  • A custom Odoo module (for example, your_module_name) where you’ll add the snippet.

For this tutorial, we’ll be working inside a module named your_module_name.

Step 1: Module Structure

To create a custom snippet, your module should have the following structure:

/your_module_name/
+-- __init__.py
+-- __manifest__.py
+-- controllers/
¦   +-- main.py
+-- static/
¦   +-- src/
¦       +-- js/
¦       ¦   +-- snippet.js
¦       +-- images/
¦           +-- snippets/
¦               +-- banner.jpg
+-- views/
¦   +-- snippet_views.xml

Here’s a quick overview of what each file does:

  • controllers/main.py: Handles the backend logic for fetching partner data.
  • static/src/js/snippet.js: Contains the OWL component that manages the frontend behavior.
  • views/snippet_views.xml: Sets up the snippet template and hooks it into the website builder.
  • static/src/images/snippets/banner.jpg: A thumbnail image to represent the snippet in the website editor.

Don’t forget to update your __manifest__.py to include the necessary dependencies and assets.

# -*- coding: utf-8 -*-
{
    'name': 'your_module_name',
    'depends': [
        'base', 'website',
    ],
    'data': [
            'views/snippets/snippet_template.xml'
    ],
    'assets': {
        'web.assets_frontend': [
            'your_module_name/static/src/js/*',
            'your_module_name/static/src/xml/*'
        ]
    },
}

Step 2: Creating the Controller

The controller handles the backend logic, fetching partner data to be displayed in the snippet. Create a file controllers/main.py with the following code:

# -*- coding: utf-8 -*-
from odoo import http
from odoo.http import request

class WebsiteSnippetOwl(http.Controller):
   @http.route('/get_partner_datas', type='json', auth='public', methods=['POST'])
   def get_partner_datas(self):
       """ Function to get partner details for the snippet"""
       return request.env['res.partner'].search_read([('image_1920', '!=', False)],
                                                         ['name', 'email', 'phone', 'city', 'street', 'image_1920'], limit=8)

Explanation:

  • The @http.route decorator defines a JSON endpoint /get_partner_datas accessible publicly.
  • The search_read method retrieves up to 8 partners with images, returning their name, email, phone, street and image_1920 fields.
  • The auth='public' ensures the endpoint is accessible to all website visitors.

Step 3: Creating the OWL Component

The OWL component handles the frontend logic, fetching data from the controller, and rendering it. Create a file static/src/js/snippet.js with the following code:

/** @odoo-module **/
import { useService } from "@web/core/utils/hooks";
import { registry } from "@web/core/registry";
import { useState, Component, onWillStart } from "@odoo/owl";
export class WebOwlComponentSnippet extends Component {
    static template = "your_module_name.snippet_xml";
    setup() {
        this.rpc = useService('rpc');
        this.state = useState({
            data: [],
        });
        onWillStart(async () => {
            this.state.data = await this.rpc("/get_partner_datas", {});
        });
    }
}
registry.category("public_components").add("your_module_name.snippet", WebOwlComponentSnippet);

Explanation:

  • Imports: We bring in rpc to call the backend, registry to register the component, and OWL tools like useState, Component, and onWillStart
  • Component: WebOwlComponentSnippet extends Component and uses the template Website_snippet_owl.snippet
  • Setup: In the setup method, a reactive state is created with an empty data list. Before rendering, the onWillStart hook loads partner data from the /get_partner_datas endpoint.
  • Registry: Finally, the component is added to the public_components category, so it can be used inside the website builder.

Step 4: Creating the OWL Template

The OWL template defines the HTML structure for rendering the partner data. Create a file static/src/xml/snippet.xml (or include it in your module's views) with the following code:

<?xml version="1.0" encoding="UTF-8"?>
<templates xml:space="preserve">
   <t t-name="your_module_name.snippet_xml">
       <div class="row body">
           <t t-foreach="state.data" t-as="each" t-key="each.id">
               <div class="col-lg-4">
                   <div class="card">
                       <div class="card-body">
                           <h5 class="card-title"><t t-esc="each.name"/></h5>
                           <div class="row">
                               <div class="col-6">
                                   <p class="card-text"><t t-esc="each.phone"/></p>
                                   <p class="card-text"><t t-esc="each.email"/></p>
                                   <p class="card-text"><t t-esc="each.street"/></p>
                               </div>
                               <div class="col-6">
                                   <img class="card-img-top o_img_product_square o_img_product_cover h-auto"
                                        t-attf-src="data:image/jpeg;base64,{{each.image_1920}}"/>
                               </div>
                           </div>
                           <a href="#" class="btn btn-primary">Go somewhere</a>
                       </div>
                   </div>
               </div>
           </t>
       </div>
   </t>
</templates>

Explanation:

  • Template: The t-name attribute sets the template name (your_module_name.snippet), which matches the component’s template
  • Loop: t-foreach goes through state.data and creates a card for each partner.
  • Data Binding: Partner info like name, email, phone, and address are shown using t-esc. The image will be shown as a base64-encoded JPEG.
  • Styling: We can use bootstrap classes like row, col-lg-4, card, etc. These are used to create very clean and responsive grid views.

Step 5: Creating the Snippet View

To make the snippet draggable and use it in the website from the website builder, a snippet view has to be created. Create a file views/snippet_views.xml with the following code:

<?xml version="1.0" encoding="utf-8"?>
<odoo>
    <template id="partner_snippet_template" name="Partner
 Snippet">
        <section class="partner_section">
            <div class="container">
                <h1>Our Partners</h1>
                <owl-component name="your_module_name.snippet"/>
            </div>
        </section>
    </template>
 <template id="partnet_component_snippet" inherit_id="website.snippets"
         name="Custom Highlight Snippet">
      <xpath expr="//div[@id='snippet_structure']/div[hasclass('o_panel_body')]"
            position="inside">
            <t t-snippet="your_module_name.partner_snippet_template"
           t-thumbnail="/partner_snippet_template/static/src/images/snippets/banner.jpg"/>
      </xpath>
</template>
</odoo>

Explanation:

  • Snippet Template: partner_snippet_template this is the main block area of the snippet, including a name heading of the OWL component.
  • Snippet Integration: The partner_component_snippet template extends website.snippets in the website module and makes the snippet available in the website builder under the "Structure" category on the website editor.
  • Thumbnail: The t-thumbnail attribute in odoo defines the preview image for the snippet when shown in the website editor.
  • Note: Please don’t forget to replace your_module_name with the name of your original module name and confirm that the image and files exist at the specified location.

Conclusion

Creating a custom snippet in Odoo 17 with OWL enables you to add engaging and interactive elements to your website. You can connect the module backend controller from the UI component and a snippet template to build reusable blocks, like a partner section. With OWL’s easy reactive system and Odoo’s website builder, it’s simple to create modern and useful snippets that fit what you need.

To read more about How to Create Website Snippets using OWL Components in Odoo 18, refer to our blog How to Create Website Snippets using OWL Components in Odoo 18


If you need any assistance in odoo, we are online, please chat with us.



0
Comments



Leave a comment



whatsapp_icon
location

Calicut

Cybrosys Technologies Pvt. Ltd.
Neospace, Kinfra Techno Park
Kakkancherry, Calicut
Kerala, India - 673635

location

Kochi

Cybrosys Technologies Pvt. Ltd.
1st Floor, Thapasya Building,
Infopark, Kakkanad,
Kochi, India - 682030.

location

Bangalore

Cybrosys Techno Solutions
The Estate, 8th Floor,
Dickenson Road,
Bangalore, India - 560042

Send Us A Message