Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variables to layout?

Tags:

php

yii

I know how to pass variable from controller into a view:

$this->render('view_name', array('variable_name'=>'variable_value'));

however I'd like to pass some variables to layout. The only connection between controller and layout seems to be the public $layout attribute in controller class, like this:

public $layout='//layouts/column2';

However, I do not see a way to pass a variable to it?

like image 608
Milan Babuškov Avatar asked Aug 14 '11 17:08

Milan Babuškov


2 Answers

It doesn't really seem to be set up to do that easily from what I can tell, so if you are relying on it to pass a lot of data, you might want to think of a different way to set up your application.

A couple ways that you could do it are to use the Yii params via

Yii::app()->params['myvar'] = $mixed;

which you can set in the controller and access in the layout. Otherwise you can use regular PHP global vars, with all the issues that approach entails.

In your controller you would do something like:

global $testvar;
$testvar = 'hello';

and in the layout:

echo $GLOBALS['testvar'];

(Even if it's not in a function, you still need to retrieve it via GLOBALS.)

You could pass an object this way for more structured data, but you are still using a global var. Another, possibly even less desirable method, would be via a session var, e.g., Yii::app()->session['myvar'] or a Yii "flash message".

like image 93
ldg Avatar answered Nov 17 '22 09:11

ldg


Alternatively, you could add a property in the Controller such as

class SiteController extends CController {

    public $myvar;
//...

And then output it in the layout (//layouts/column2)

echo isset($this->myvar) ? $this->myvar : '';
like image 14
Petra Barus Avatar answered Nov 17 '22 08:11

Petra Barus