Creating Dynamic Website Snippets in Odoo 18: A Developer’s Guide

Creating Dynamic Website Snippets in Odoo 18: A Developer’s Guide

Odoo 18 has revolutionized website building with its enhanced dynamic snippet system, allowing developers to create interactive, data-driven components that elevate user engagement. Dynamic snippets pull content from databases or external APIs, enabling real-time updates and personalized experiences. In this guide, we’ll walk through building a dynamic carousel snippet in Odoo 18, integrating XML, JavaScript, and backend logic.


1. Understanding Dynamic Snippets

Dynamic snippets differ from static ones by leveraging server-client interactions to populate content dynamically. For instance, a carousel displaying product highlights or blog posts requires fetching data from Odoo models or external sources. This flexibility makes dynamic snippets ideal for eCommerce, event listings, or news feeds .

Key Features of Dynamic Snippets:

  • Data-Driven Content: Load records from Odoo models (e.g., products, blog posts).
  • Interactive Elements: Add sliders, forms, or AJAX-based updates.
  • Customization: Users can tweak settings via the website editor’s Customize tab .

2. Prerequisites

Before diving in, ensure you have:

  • Odoo 18 Installed: Either on a local server or cloud instance.
  • Development Environment: Familiarity with Python, XML, and JavaScript.
  • Custom Module Setup: A dedicated module to organize snippet files .

Step 1: Module Structure

Start by creating a module (e.g., website_dynamic_snippets) with this __manifest__.py:

{  
  'name': 'Dynamic Carousel Snippet',  
  'version': '1.0',  
  'depends': ['website'],  
  'data': [  
    'views/snippets.xml',  
    'views/snippet_registry.xml',  
  ],  
  'assets': {  
    'web.assets_frontend': [  
      'website_dynamic_snippets/static/js/snippet_dynamic.js',  
      'website_dynamic_snippets/static/css/snippet_dynamic.css',  
    ],  
  },  
}

This manifest links XML templates, JavaScript, and CSS assets .

Step 2: Define the Snippet Template

In views/snippets.xml, create the carousel structure using Bootstrap classes for responsiveness:

<template id="snippet_dynamic_carousel" inherit_id="website.snippets">  
  <xpath expr="//div[@id='wrap']" position="inside">  
    <div class="o_snippet_dynamic_carousel" data-snippet="dynamic_carousel">  
      <div class="carousel-inner" data-oe-model="carousel.items"></div>  
      <!-- Navigation arrows -->  
    </div>  
  </xpath>  
</template>

The data-oe-model attribute binds the snippet to a backend model .

Step 3: Add JavaScript for Dynamic Loading

In static/js/snippet_dynamic.js, use Odoo’s publicWidget to fetch data:

odoo.define('website_dynamic_snippets.snippet_dynamic', function (require) {  
  "use strict";  
  var publicWidget = require('web.public.widget');  

  publicWidget.registry.DynamicCarousel = publicWidget.Widget.extend({  
    selector: '.o_snippet_dynamic_carousel',  
    start: function () {  
      this._loadItems();  
    },  
    _loadItems: function () {  
      var self = this;  
      this._rpc({  
        route: '/carousel/items',  
        params: {},  
      }).then(function (items) {  
        items.forEach(item => {  
          self.$('.carousel-inner').append(`  
            <div class="carousel-item">  
              <img src="${item.image_url}" />  
              <div class="carousel-caption">${item.caption}</div>  
            </div>  
          `);  
        });  
      });  
    },  
  });  
});

This code fetches data from a backend controller endpoint /carousel/items .

Step 4: Backend Integration

Create a controller (controllers/main.py) to serve carousel data:

from odoo import http  
from odoo.http import request  

class CarouselController(http.Controller):  
    @http.route('/carousel/items', type='json', auth='public')  
    def fetch_carousel_items(self):  
        return request.env['carousel.item'].search([]).read(['image_url', 'caption'])

Ensure the model carousel.item is defined with relevant fields .


4. Styling and Snippet Registration

  • CSS: Style the carousel in static/css/snippet_dynamic.css using Flexbox for smooth transitions .
  • Registry: Add the snippet to the website editor via snippet_registry.xml:
    <template id="website.snippet_list" inherit_id="website.snippet_list">  
    <xpath expr="//div[@id='snippet_structure']" position="inside">  
      <div class="o_snippet_thumbnail" data-snippet="dynamic_carousel">  
        <img src="/module/static/img/carousel_thumb.png"/>  
        <span>Dynamic Carousel</span>  
      </div>  
    </xpath>  
    </template>
    
    Avoid XPath errors by targeting snippet_structure correctly .

5. Testing and Advanced Customization

  • Test: Restart Odoo, install the module, and drag the snippet into the editor. Verify data loading .
  • Options: Add snippet options (e.g., filter categories, animation speed) using data-selector attributes and JavaScript event hooks like onFocus or onBuilt .

Conclusion

Dynamic snippets in Odoo 18 empower developers to create immersive, data-rich web experiences. By combining XML templates, JavaScript interactivity, and backend integration, you can build components like carousels, product grids, or live forms that adapt to user needs. For further exploration, dive into Odoo’s official documentation on dynamic content blocks or experiment with AJAX-driven forms .

Ready to elevate your Odoo website? Start coding your dynamic snippets today!


References:

Administrator

Administrator

0 Comments

Leave a Reply

Your email address will not be published. Required fields are marked *