Back to Top

Add global variables to javascript objects and smarty templates using PrestaShop 1.7

Updated 29 December 2022

In this blog, We are going to learn how we can assign global variables from the module. These assigned variables will work for javascript & smarty templates.

So let’s start the practical..!

Firstly, we need to register a PrestaShop hook in an existing module or any custom module. For this practical, we have created a demo module.

$this->registerHook("actionFrontControllerSetVariables");

Note: This hook is available from PrestaShop 1.7.5.0.

Now we need to create a function related to this hook & assign the required variable.

Searching for an experienced
Prestashop Company ?
Find out More
public function hookActionFrontControllerSetVariables($params)
{
    $variables = array(
        'module_display_name' => 'This text is coming from '.$this->displayName,
    ); 

    return $variables;    
}

After assigning the variables you can call these assigned variables anywhere in the whole PrestaShop templates OR javascript. Let’s see the examples.

Smarty process to use assigned variables:

We have added some custom code in product.tpl to show the assigned variable data.

Path: _ROOT_DIR_/themes/classic/templates/catalog/product.tpl

{* Code added for testing *}
<div class="alert alert-success">
    {$modules.wkdemo.module_display_name}
</div>
{* Code end *}
Selection_101
Selection_102

Now you can see the reflection on the product page in the front office. Check the below image.

Front_End

Javascript process to use assigned variables:

We have added some custom code in theme.js to alert the value of the assigned variable.

Path: _ROOT_DIR_/themes/classic/assets/js/theme.js

$(document).ready(function() {
    var moduleDisplayName = prestashop.modules.wkdemo.module_display_name;

    alert(moduleDisplayName);
});
Selection_103

Note: You can call the assigned variable from any Javascript file OR Smarty templates.

That’s all about this blog. Hope it will help you.

If you are facing any issues or have any doubts about the above process, please feel free to contact us through the comment section.

Also, you can explore our PrestaShop Development Services and a large range of quality PrestaShop Modules.

For any doubt contact us at [email protected]

. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


Be the first to comment.

Back to Top

Message Sent!

If you have more details or questions, you can reply to the received confirmation email.

Back to Home