I understood that if I want to make my own template variable in PrestaShop, I would use code like this:
$this->context->smarty->assign( 'varName', 'varValue' );
I also understood that the right way to add this is putting it into a controller... and it all works...
What I can't figure out is how to do this in one place but still being able to access the template variable in ALL templates (my theme's .tpl files)?
PS: Adding it to all controllers seems redundant... I tried to google it out, but I guess I am putting bad keywords to search for...
So I found a solution.
What you want to do is to put your variable definition in some "general" controller - for frontend it is the FrontController
. A better way then to edit the core file, is to make an override so I will show you all you need to do - considering PrestaShop 1.6 :
Create a file called FrontController.php
and put it in override/classes/controller
Create a content of this file - handy method to override is initHeader()
, because the variable will be available in header.tpl
and all templates that are using it
(tested in header.tpl
and index.tpl
).
Content of override/classes/controller/FrontController.php
:
class FrontController extends FrontControllerCore {
public function initHeader(){
//create your variable
self::$smarty->assign('yourVariable', 'valueOfYourVariable');
//call original method, to maintain default behaviour:
return parent::initHeader();
}
}
Load the override=> go to cache
directory (from shop root) and edit file called class_index.php
:
'FrontController'
or "FrontController"
)'path' => 'WHATEVER',
override/classes/controller/FrontController.php
so you will get: 'path' => 'override/classes/controller/FrontController.php',
Use your variable freely in template files as {$yourVariable}
Reference: http://doc.prestashop.com/display/PS16/Overriding+default+behaviors
you can do with modules also, prestashop provides hooks, we can use the header hook inside our module and pass the variables to smarty from the header hook function. The header hook is available on all pages
public function hookHeader($params)
{
$this->smarty->assign(array('var1' => 'value 1', 'var2' => 'value 2', 'var3' => 'value 3',));
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With