Search code examples
prestashopsmartyprestashop-1.7

Pass variable from custom hook to TPL file


I have created a custom module. Which simply registers a hook, whose only function is to obtain a list of products of a specific category.

The hook works perfectly. Then I call it from a TPL file, it is called correctly, but when I try to get the hook variable from the TPL file, I can't.

This is the code of my Hook.

    public function hookDisplayCaronteCategories($params){

        if (array_key_exists('max', $params)) {
            $max = $params['max'];
        }
        else{
            $max = 1000;
        }

        $category = new Category(
            $params['id_category'], //id de la categoría
            (int)Context::getContext()->language->id // id del idioma
        );
        $caronteProducts = $category->getProducts(
            (int)Context::getContext()->language->id, //id lenguaje
             1, //número de páginas
             $max, //productos por páginas
             'date_add', //order by
             'DESC', //order way
             false, //get total
             true, //mostrar activos
             false, // random
             1, // random_number_products
             true, //check access
             Context::getContext() //context
        );
        $this->smarty->assign(array('caronteProducts', $caronteProducts));
        return $this->display('http://localhost/rapture/themes/classic_child/templates/cms/page-6.tpl');
    }

The var_dump function at the end correctly displays the product data.

enter image description here

However, if I do a var_dump from the tpl, the function returns null. This is how I call the hook from the tpl.

      {hook h="displayCaronteCategories" id_category=11}
      {$caronteProducts|var_dump}

And this is what I get:

enter image description here

How can I get the hook variable in the tpl file?

Thank you.


Solution

  • in which TPL are you trying to print the $caronteProducts variable ?

    You'll need to fetch/render your TPL inside your hook, and the variable will be available there as there is no global scope..

    Something like :

    $this->smarty->assign(array('caronteProducts', $caronteProducts));
    return $this->display(dirname(__FILE__), 'views/templates/hook/caronteproducts.tpl');