Jump to content

[SOLVED] Create variable accessible through all templates in PrestaShop


jave.web

Recommended Posts

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


 


(this copy-post , also available on http://stackoverflow.com/questions/32154593/create-variable-accessible-through-all-templates-in-prestashop )


Edited by jave.web (see edit history)
  • Like 1
Link to comment
Share on other sites

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

Edited by jave.web (see edit history)
  • Like 2
  • Thanks 1
Link to comment
Share on other sites

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
×
×
  • Create New...