0
votes

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

3
Why would you want to use smarty in javascript files? You want smarty variables in javascript? - TheDrot
@TheDrot - it would be cool if could even use smarty if satements to build the javascript file. yeah but the most of it it's variables. - ufk

3 Answers

2
votes

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.

1
votes

You can simply do this in the tpl file:

<script>var = '{$var}';</script>

and use your var in the javascript file.

Source: https://www.prestashop.com/forums/topic/589645-unknown-tag-addjsdef-error/?tab=comments#comment-2490210

0
votes

Safer way to declare your vars without mymodule array,

Media::addJsDef(array('var1' => $myphpvar));
Media::addJsDef(array('var2' => $myphpvartwo));

this way you DONT need

let var1 = mymodule.var1;

Why this better? Because 'let var1' cause error in iphone safari browser.