Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create variable accessible through all templates in PrestaShop

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...

like image 380
jave.web Avatar asked Sep 06 '25 03:09

jave.web


2 Answers

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 :

  1. Create a file called FrontController.php and put it in override/classes/controller

  2. 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();
    }
}
  1. Load the override=> go to cache directory (from shop root) and edit file called class_index.php:

    • find array with key "FrontController" (search for 'FrontController' or "FrontController")
    • in this array change "WHATEVER" in 'path' => 'WHATEVER',
      to override/classes/controller/FrontController.php so you will get:
      'path' => 'override/classes/controller/FrontController.php',
  2. Use your variable freely in template files as {$yourVariable}

Reference: http://doc.prestashop.com/display/PS16/Overriding+default+behaviors

like image 198
jave.web Avatar answered Sep 07 '25 23:09

jave.web


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',));
}
like image 26
Gofenice Technologies Avatar answered Sep 07 '25 23:09

Gofenice Technologies