Skip to content

Unleash the Power: Master Odoo 18 Public Components in 7 Easy Steps

odoo 18 public component

Unleash the Power: Master Odoo 18 Public Components in 7 Easy Steps

Are you ready to elevate your Odoo frontend development? With the advent of Odoo 18 public component capabilities, developers now have more robust tools than ever to craft dynamic, engaging user interfaces, especially within the customer portal. This comprehensive guide will not only persuade you of the immense value of these new components but will also walk you step-by-step through creating and integrating your very own.

Before we dive in, please note that this article is inspired by an excellent deep-dive video. You can find the original content and further details here: https://www.youtube.com/watch?v=IPsszm6bC0s.

Prerequisites for this Tutorial:

  • An Odoo 18 environment ready for development.
  • A basic understanding of Odoo module structure and Python.
  • Familiarity with JavaScript, XML (QWeb), and HTML.
  • Your preferred text editor (e.g., Visual Studio Code).
  • Access to your Odoo server and file system.

Let’s embark on this journey to master the Odoo 18 public component!


1. Why Odoo 18 Public Components are a Game-Changer

Odoo’s frontend has been in a constant state of evolution, moving towards a more modern, reactive, and component-based architecture. This shift is largely driven by OWL (Odoo Web Library), a lightweight JavaScript framework that underpins the new Odoo client. In Odoo 18, this transition brings the exciting ability to define and use public components.

Previously, extending Odoo’s frontend often involved less structured methods or proprietary widgets. Now, with the official support for an Odoo 18 public component, you can:

  • Build Highly Interactive Interfaces: Create dynamic sections that update in real-time without full page reloads.
  • Enhance User Experience: Provide a smoother, more responsive interaction, especially crucial in customer-facing areas like the portal. Imagine a personalized dashboard showing real-time updates of customer data or a dynamic list of courses that can be filtered and sorted.
  • Improve Code Organization: Encapsulate UI logic and templates into reusable units, leading to cleaner, more maintainable codebases.
  • Future-Proof Your Development: Align your custom developments with Odoo’s strategic direction for its web client, which increasingly relies on OWL components.

This is more than just a new feature; it’s a fundamental improvement for anyone serious about Odoo frontend development.


2. Odoo 18 Public Components: Core Concepts and Key Considerations

At its heart, an Odoo 18 public component is a combination of a JavaScript class (defining its behavior and state) and an XML template (defining its visual structure using QWeb). These components are specifically designed for the frontend, meaning they execute in the user’s browser.

Key Concepts:

  • OWL Framework: Your components will be built using OWL, Odoo’s proprietary component-based framework. If you’re familiar with React or Vue.js, you’ll find many similar concepts.
  • Public Registry: Public components are registered in a special registry.category("public_components"). This makes them discoverable and usable throughout the frontend.
  • Unique Naming: To avoid conflicts, each public component needs a unique identifier, typically following the pattern your_module_name.your_component_name.
  • Frontend Assets: All JavaScript and XML files for your component must be declared in the web.assets_frontend bundle within your module’s __manifest__.py.

Important Limitations and Best Practices:

While powerful, it’s crucial to understand the limitations of client-side rendered components:

  • SEO Impact: Content rendered purely client-side via JavaScript can sometimes pose challenges for search engine crawlers (like Googlebot) if not handled carefully. Google has improved its crawling of JavaScript, but for critical public pages that need strong SEO, fully server-side rendered content is generally safer.
  • Layout Shift: If your component fetches data asynchronously and renders after the initial page load, users might experience a “layout shift” – where content jumps or resizes as elements appear. This can degrade user experience.
  • Performance: Complex or poorly optimized components can impact page load times and overall performance.

The Ideal Use Case: The Odoo Customer Portal

Given these considerations, the customer portal is an exemplary use case for an Odoo 18 public component. Why? Because portal pages are typically private, requiring users to log in. This means:

  • SEO is less critical: These pages are not indexed by public search engines.
  • Enhanced User Experience is paramount: Logged-in users expect a smooth, interactive experience tailored to their needs.
  • Dynamic Data Display: The portal often needs to display personalized data (like a list of courses, orders, or support tickets) that benefits greatly from dynamic rendering.

So, while it’s tempting to use this new feature everywhere, apply it strategically where it makes the most sense – the portal being a prime example.


3. Setting Up Your Odoo 18 Module for Public Components

Our goal is to create a module named elearning_portal that will host our first Odoo 18 public component to display a list of courses on the customer portal.

Step 1: Create the Basic Module Structure

Navigate to your Odoo addons directory (or your extra-addons path). Use the following command to create the necessary directories. This works well on Mac and Linux; Windows users might need to create these folders manually.

mkdir -p elearning_portal/{controllers,static/src/{js,xml},views}

This command will create a module folder with the following structure:

elearning_portal/
├── controllers/
├── static/
│   └── src/
│       ├── js/
│       └── xml/
└── views/

Step 2: Create __init__.py Files

Create an empty __init__.py file in both the elearning_portal directory and the elearning_portal/controllers directory. These files signal to Python that these are packages.

  • elearning_portal/__init__.py
  • elearning_portal/controllers/__init__.py

Step 3: Create __manifest__.py

Create a file named __manifest__.py in the root of your elearning_portal directory. Populate it with the following code. Remember to update placeholders like ‘Your Name’ and ‘www.example.com’. The assets key is crucial here for declaring your frontend files.


{
    'name': 'E-learning Portal',
    'summary': 'Adds a dynamic course list to the Odoo customer portal using an Odoo 18 public component.',
    'description': """
        This module demonstrates the creation and integration of an Odoo 18 public component
        to display e-learning courses directly within the customer portal.
    """,
    'author': 'Your Name',
    'website': 'www.example.com',
    'version': '1.0',
    'depends': ['base', 'portal'],  # 'portal' dependency is essential for client portal modifications
    'data': [
        'views/portal_template.xml',  # We'll create this file in a later step
    ],
    'assets': {
        'web.assets_frontend': [
            'elearning_portal/static/src/js/elearning_component.js',
            'elearning_portal/static/src/xml/elearning_component.xml',
        ],
    },
    'installable': True,
    'application': True,
    'auto_install': False,
    'license': 'LGPL-3',
}

Notice the web.assets_frontend bundle: this is where you declare all JavaScript and XML (QWeb) files that your Odoo 18 public component will use on the client side. This ensures Odoo loads them correctly in the browser.


4. Crafting Your First Odoo 18 Public Component

Now comes the exciting part: defining the component itself.

Step 1: Create the JavaScript Component File

Create a file named elearning_component.js inside the elearning_portal/static/src/js/ directory. This file will contain the OWL component’s logic.


/** @odoo-module **/

import { Component, mount } from '@odoo/owl';
import { registry } from '@web/core/registry';

// Define the ElearningComponent class, inheriting from OWL's Component
export class ElearningComponent extends Component {
    setup() {
        // Initialize component state. In a real app, this data would come from the backend.
        this.courses = [
            { id: 1, name: 'Odoo Development Masterclass' },
            { id: 2, name: 'Python for Odoo Developers' },
            { id: 3, name: 'JavaScript Fundamentals with OWL' },
            { id: 4, name: 'Advanced Odoo 18 Public Component Techniques' }
        ]; // Example Data - Replace with dynamic data fetching later
    }

    // You can add methods here to handle user interactions or fetch data
    // async fetchCourses() { ... }
}

// Associate the component with its QWeb template
ElearningComponent.template = 'elearning_portal.ElearningComponentTemplate';
// Declare properties (props) the component can receive. Currently empty.
ElearningComponent.props = {};

// Register the component in the public_components category.
// The name 'elearning_portal.elearning_component' must be unique and
// will be used to reference this component in XML templates.
registry.category("public_components").add("elearning_portal.elearning_component", ElearningComponent);

Step 2: Create the XML Template File

Create a file named elearning_component.xml inside the elearning_portal/static/src/xml/ directory. This file will contain the QWeb template that defines the component’s visual output.


<?xml version="1.0" encoding="UTF-8"?>
<templates>
    <!-- Define the QWeb template for our ElearningComponent -->
    <t t-name="elearning_portal.ElearningComponentTemplate">
        <div class="container o_elearning_courses">
            <h2 class="mt-4 mb-3 text-primary">Explore Our E-learning Catalog</h2>
            <p>Welcome to your personalized course list! Here are some of our top offerings:</p>
            <div class="list-group">
                <!-- Iterate over the 'courses' data from our JavaScript component -->
                <t t-foreach="courses" t-as="course" t-key="course.id">
                    <a href="#" class="list-group-item list-group-item-action">
                        <i class="fa fa-book me-2"/> <t t-esc="course.name"/>
                    </a>
                </t>
            </div>
            <p class="mt-3 text-muted">More courses coming soon!</p>
        </div>
    </t>
</templates>

Odoo 18 QWeb Enhancements:

  • t-key for t-foreach: Odoo 18 now strongly recommends (and sometimes mandates) the t-key attribute when using t-foreach. This helps OWL efficiently update lists by uniquely identifying each item, preventing potential rendering issues and improving performance.
  • No t-name="template_name" needed for component templates: While traditional QWeb templates might use this, component templates are directly linked via Component.template.
  • T out vs T escape: While t-esc (used above) still escapes content, T out is available for printing raw HTML or text without escaping, similar to a Python print() statement, but be cautious with T out as it can introduce XSS vulnerabilities if used with untrusted input. For displaying user-provided text, t-esc is always the safer choice.

5. Integrating Odoo 18 Public Components into the Portal

Now that our Odoo 18 public component is defined, we need to tell Odoo where to display it on the customer portal. We’ll achieve this by inheriting an existing portal template.

Step 1: Create the Portal Template File

Inside your elearning_portal/views/ folder, create a new XML file named portal_template.xml.

Step 2: Inherit and Modify the Portal Template

Add the following XML to portal_template.xml. This code will inherit the portal.portal_my_home template and insert our elearning_component into a specific section of the portal page.


<odoo>
    <!-- Inherit the main customer portal home page template -->
    <template id="portal_my_home_elearning" inherit_id="portal.portal_my_home" name="E-learning Courses on Portal Home">
        <!-- Use xpath to precisely target where to insert our component -->
        <!-- We're targeting a div with the class 'o_portal_docs' and inserting our component inside it -->
        <xpath expr="//div[hasclass('o_portal_docs')]" position="inside">
            <!-- This is how you call an Odoo 18 public component's template -->
            <!-- The 't-call' instruction renders the QWeb template associated with our component. -->
            <t t-call="elearning_portal.ElearningComponentTemplate"/>
        </xpath>
    </template>
</odoo>

The xpath expression //div[hasclass('o_portal_docs')] is a powerful way to locate specific elements within existing Odoo templates. It ensures your custom component is placed accurately without altering the original template’s structure. If o_portal_docs isn’t suitable, inspect your portal page to find a better hook.


6. Powering Up Your Development Workflow

For a smooth development experience with an Odoo 18 public component, consider these tips:

A. Automatic Asset Reloading:
Modify your Odoo configuration file (odoo.conf) to enable automatic QWeb and XML reloading. This saves you from constantly updating your module.


[options]
...
qweb_reload = True
...

B. Launching Odoo with Development Parameters:
When starting Odoo, you can use parameters to automatically refresh modules and specify your database. If you use VS Code, you can configure a launch.json file for this:


{
    "version": "0.2.0",
    "configurations": [
        {
            "name": "Odoo Development",
            "type": "python",
            "request": "launch",
            "program": "${workspaceFolder}/odoo-bin",
            "args": [
                "-c", "odoo.conf",
                "--addons-path", "/path/to/your/addons", // Adjust this path
                "-d", "your_database_name",
                "--dev", "xml,qweb,js", // Automatically reloads XML, QWeb, and JS changes
                "-u", "elearning_portal" // Update your module on startup for initial changes
            ],
            "console": "integratedTerminal",
            "justMyCode": true
        }
    ]
}

Remember to replace /path/to/your/addons and your_database_name with your actual values.


7. Module Installation and Verification

Finally, let’s bring your Odoo 18 public component to life!

Step 1: Update the Module List
After making changes to __manifest__.py, go to your Odoo backend, navigate to “Apps,” and click “Update Apps List.”

Step 2: Install the Module
Search for “E-learning Portal” in the Apps list and click “Install.”

Step 3: Access the Customer Portal
Log in to the customer portal (usually accessible via /my from your Odoo instance). You should now see the “Explore Our E-learning Catalog” section with your list of courses, dynamically rendered by your new Odoo 18 public component.

Step 4: Debugging and Inspection

  • Activate Developer Mode: In Odoo, enable developer mode (via the “Settings” menu or by adding ?debug=1 to your URL). This often provides more detailed error messages.
  • Browser Developer Tools: Use your browser’s “Inspect Element” (F12) to examine the rendered HTML. You’ll see your component’s div and its contents. Look at the “Console” tab for any JavaScript errors.
  • Odoo Component Debugger (Browser Extension): Consider installing browser extensions for Firefox or Chrome that specifically help debug Odoo OWL components. These tools can show you the component tree and its internal state, which is invaluable for complex components.
  • console.log(): Don’t shy away from using console.log() in your JavaScript to output variable values and track execution flow.

Conclusion: Embracing the Future of Odoo Frontend

You’ve successfully built and integrated your first Odoo 18 public component! This tutorial has guided you through the entire process, from setting up your module to defining the component’s logic and template, and finally integrating it into the Odoo customer portal. You’ve also gained a crucial understanding of its capabilities, limitations, and best practices.

The power of an Odoo 18 public component lies in its ability to create more dynamic, interactive, and user-friendly frontend experiences. While respecting its current limitations, particularly regarding SEO for public-facing sites, its utility in private, logged-in areas like the portal is undeniable. This is a significant step forward in modernizing Odoo’s web client, offering developers more control and flexibility.

Continue to experiment, explore dynamic data fetching from backend controllers, and leverage the full potential of OWL components in Odoo 18. The future of Odoo frontend development is here, and you’re now equipped to be a part of it.

Want to dive deeper into Odoo development? Explore more Odoo 18 development tips and tricks on our blog!

Further Resources:


Discover more from teguhteja.id

Subscribe to get the latest posts sent to your email.

Leave a Reply

WP Twitter Auto Publish Powered By : XYZScripts.com