How to pass a variable from app_controller to the layout

I am new to CakePhp and I am trying to pass a variable from my app_controller.php to my default.ctp.

I tried this in my app_controller.php:

function beforeFilter(){
$this->set('my_var', $my_var_to_pass);
}

But when I do this in my default.ctp:

echo $my_var;

I got it:

Notice (8): Undefined variable: my_var [APP\views\layouts\default.ctp, line 72]

I am using Cake 1.3!

Some ideas?

Thank!

+3
source share
4 answers

The only thing I can think of is that you are not using 1.3, as you say, and infact 1.2, as it had code that converted some_var to someVar, so try

$this->set('myvar', $my_var_to_pass); 
echo $myvar 
// or 
$this->set('my_var', $my_var_to_pass); 
// and 
echo $myVar
+3
source

A good way to pass vars from app__controllerto any layout is to use the function beforeFilter()in app_controller.

These are the same functions as when using Auth:

function beforeFilter() {
    $this->set('your_var', 'Data for the var');}
+2

SQuat, CakePHP ? 69, 1,2 1,3. , , debug ($ this- > viewVars).

1.2 viewVars camelized()... 1.3, .

+1

"my_var" , "_for_layout" . :

$this->set('my_var_for_layout', $my_var_to_pass);

, , :

echo $my_var_for_layout;
-2

Source: https://habr.com/ru/post/1789288/


All Articles