Question

is there any way to add JS and CSS tags just for the page where the module is contained?

If i use the code snippet

$this->context->controller->addjs('js/file.js', 'all');

in the "hookHeader", the script is added for the whole website (index, cms pages, etc.) where hook is used.

Thanks, any help would be appreciated.

Was it helpful?

Solution

If you want to add a js file only in page product and category for example, you can do this :

public function hookDisplayHeader($params)
{
    $allowed_controllers = array('product', 'category');
    $_controller = $this->context->controller;
    if (isset($_controller->php_self) && in_array($_controller->php_self, $allowed_controllers)) {
        $this->context->controller->addCss($this->_path . 'css/front.css', 'all');
        $this->context->controller->addJs($this->_path . 'js/front.js');
    }

}

OTHER TIPS

Yes you can do it easily. What you need to do it to call addJs or addCss in the desired hook function only. For example, if you are hooking your module at left column on certain pages only, then if you call

$this->context->controller->addjs('js/file.js', 'all');

at your hookLeftColumn (what ever the method name is nowadays :P ), then that js or css file will be only used when that module is displayed.

Or you can just place that css / js file directly in the template.

If your module will appear on specific pages, you can define "Exceptions" - the same that can be defined via Back Office > Modules > Positions > Transplant a module.

This way the hookDisplayHeader for that module will not be even executed and no CSS and JS files will be added. This is a better solution from a performance view point.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top