Search code examples
odooqwebodoo-15

odoo15: How can I load js in qweb template?


I need to add events in some buttons in qweb template or maybe make a widget for this template. But I can't load js in this template, even if I add js file in web.assets_backend or web.assets_frontend.

controller.py

from odoo import http
class LogData(http.Controller):
    @http.route("/log_data", type="http", auth="user")
    def log_data_view(self, **kwargs):
        return http.request.render(
            "table_relation.log_data_template"
        )

log_data_template.xml

<odoo>

  <template id="log_data_template" name="Log Data">
    <t t-call="web.layout">
      <t t-set="head">
        <t t-call-asssets="web.assets_common" t-js="false"/>
        <t t-call-asssets="web.assets_frontend" t-js="false"/>
      </t>

      <div id="wrap" class="container">
        <h1>Log Data</h1>
        <div class="o_log_data">
          <button id="start-log">日志</button>
          <button id="cancel-log">停止</button>
          <div id="log-content" style="height:500px;overflow: scroll;"/>
        </div>
        <button type="button" class="demo-btn">demo button</button>
      </div>
    </t>
  </template>


</odoo>


log_data.js

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

console.log('==========')

publicWidget.registry.LogData = publicWidget.Widget.extend({
    selector: '.o_log_data',
    events: {
        'click #start-log': '_startLog',
        'click #cancel-log': '_cancelLog',
    },

    init: function () {
        console.log('o_log_data')
    },
    start: function () {
        console.log('o_log_data')
    },
    _startLog: function () {
        console.log('_startLog')
    },
});

publicWidget.registry.DemoBtn = publicWidget.Widget.extend({
    selector: '.demo-btn',
    events: {
        click: '_onClick'
    },
    _onClick: function (e) {
        console.log('_onClick')
    },
});
})

manifest.py

'assets': {
        'web.assets_backend': [
         ...
         'table_relation/static/src/js/log_data.js',
        ]
        'web.assets_frontend': [
         ...
         'table_relation/static/src/js/log_data.js',
        ]
         ...
}

enter image description here

It seems not to load assets_backend bundle on this page, and log_data.js is not working.


Solution

  • As per the code you have mentioned above, it seems like you are trying to create a controller i.e a route that can be accessed by the User only but from the website side like the portal or eCommerce part.

    So if that is the case, then you need to add your js files to web.assets_frontend instead of web.assets_backend in manifest.py file.