Search code examples
javascriptsmartyprestashopprestashop-1.7

using smarty template engine in registered javascript files with prestashop 1.7


I'm writing Prestashop 1.7.2.1 module.

In that module when I want to register a javascript file I connect to the hook actionFrontControllerSetMedia and use registerJavascript like so:

    $this->context->controller->registerJavascript('module-tuxinmodcartype-carsearch-js','modules/'.$this->name.'/js/displaytop.js');

this loads the javascript properly but I can't use smarty template engine in those javascript files.

is there a way to do that ? :)

if not... should I just add all my javascript files inline ?

update

so I added this to my hook function:

 Media::addJsDef(['tuxinmodcartype'=>array(
        'car_companies'=>$this->tuxDb->getCompanyNamesArray()
    )]);

and this my js file:

$(function() {
    var options = {
        data: tuxinmodcartype.car_companies,
        list: {
            match: {
                enabled: true
            }
        }
    };

    $('#company-name-input').easyAutocomplete(options);

});

and I get the error ReferenceError: tuxinmodcartype is not defined


Solution

  • For accessing variables in javascript you can assign them in your controllers with:

    Media::addJsDef(array(
        'mymodule' => array(
            'var1' => 'yes',
            'var2' => 'no'
        )
    ));
    

    Then you can use them in your javascript or through console:

    let var1 = mymodule.var1;
    let var2 = mymodule.var2;
    

    Building javascript files with smarty... I guess it's better to split javascript into more files and load them through controller based on conditions. Or use the above definition for variables to control execution path in your javascript.