Reputation: 45
I'm trying to figure out how to use global View variables in Kohana properly. I have a Controller_Base
class which provides a basic layout of a page:
abstract class Controller_Base extends Controller_Template {
public $template = 'base';
public function before () {
parent::before();
View::set_global('title' , '');
}
}
My base.php
view looks like this:
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $content; ?>
</body>
</html>
And I also have a Controller_Welcome
class inheriting from Controller_Base
:
class Controller_Welcome extends Controller_Base {
public function action_index () {
$this->template->content = View::factory('welcome');
}
}
welcome.php
view looks like this:
<?php $title = 'Some title'; ?>
<h1>Hello, world!</h1>
The question is: how can I modify that global $title
variable from welcome.php
so in the end of the view chain base.php
could get it? I don't want to put anything related to views into a controller.
Upvotes: 3
Views: 1591
Reputation: 16873
You should be able to do it like this:
welcome.php
view:
<?php View::set_global('title', 'Some title'); ?>
<h1>Hello, world!</h1>
Controller_Welcome
class:
class Controller_Welcome extends Controller_Base {
public function action_index () {
$this->template->content = View::factory('welcome')->render();
}
}
Note the call to render()
- it is very important in order for this to work! In the normal execution flow, the base
view will be evaluated first, followed by the inside. In order for the call to set_global
to be made before the base is rendered, you must explicitly render the inside first.
Aside: If you are doing any significant templating stuff, you really should consider using Kostache with proper "ViewModel" classes, which are a much more elegant way to solve this problem.
Upvotes: 1