0

I'm developing a module for OpenCart 3.x and I'm trying to insert some JavaScript code into website's front via $this->load->view() method but cannot get it to work, as the JS code doesn't appear in the DOM.

Here's an excerpt of my code:

/catalog/controller/extension/module/mymodule.php

class ControllerExtensionModuleMyModule extends Controller {

    public function index() {

        $this->load->language('extension/module/mymodule');

        $this->load->model('checkout/order');
        $this->load->model('setting/setting');
        $this->load->model('design/layout');
        $this->load->model('catalog/category');
        $this->load->model('catalog/manufacturer');
        $this->load->model('catalog/product');
        $this->load->model('catalog/information');

        $data['js_output'] = "Some JS output"; 

        return $this->load->view('extension/module/mymodule', $data);
    }
}

catalog/view/theme/default/template/extension/module/mymodule.twig

<script type="text/javascript">
console.log('This is working!");
</script>

Am I missing something?

Carol-Theodor Pelu
  • 906
  • 2
  • 10
  • 26

2 Answers2

0

Add an external javascript file via controller like this:

$this->document->addScript('catalog/view/javascript/my-external-script.js');

But if it's a block of javascript code, you don't need to edit controller file, just add it to your view file (twig or tpl):

<script type="text/javascript">
    console.log("This is working!");
</script>

Finally you may need to clear caches (vqmod, ocmod, twig etc ...).

EDIT

If you want to prepare your javascript code in the controller, follow this:

controller

$data['js_output'] = 
'<script type="text/javascript">
    console.log("This is working!");
</script>';

Twig

{{ js_output }}
DigitCart
  • 2,980
  • 2
  • 18
  • 28
0

I have finally fixed the issue. It was a problem with the install() method not correctly inserting and loading the design/layout ($this->model_design_layout->getLayouts()).

If your module needs to insert a layout into the layout_module table, make sure you have the correct layout_id, code(which must be your module name), position (i.e: 'content_bottom') and sort_order(which often times is > 90).

Carol-Theodor Pelu
  • 906
  • 2
  • 10
  • 26