gpt4 book ai didi

php - Kohana 中的全局 View 变量

转载 作者:搜寻专家 更新时间:2023-10-31 22:05:04 24 4
gpt4 key购买 nike

我正在尝试弄清楚如何在 Kohana 中正确使用全局 View 变量。我有一个 Controller_Base提供页面基本布局的类:

abstract class Controller_Base extends Controller_Template {

public $template = 'base';

public function before () {
parent::before();
View::set_global('title' , '');
}
}

我的 base.php View 看起来像这样:

<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title><?php echo $title; ?></title>
</head>
<body>
<?php echo $content; ?>
</body>
</html>

我还有一个Controller_Welcome继承自 Controller_Base 的类:

class Controller_Welcome extends Controller_Base {

public function action_index () {
$this->template->content = View::factory('welcome');
}
}

welcome.php View 看起来像这样:

<?php $title = 'Some title'; ?>
<h1>Hello, world!</h1>

问题是:如何修改全局 $title来自 welcome.php 的变量所以在 View 链的末尾 base.php能得到吗?我不想将与 View 相关的任何内容放入 Controller 。

最佳答案

你应该可以这样做:

welcome.php View :

<?php View::set_global('title', 'Some title'); ?>
<h1>Hello, world!</h1>

Controller_Welcome 类:

class Controller_Welcome extends Controller_Base {

public function action_index () {
$this->template->content = View::factory('welcome')->render();
}
}

请注意对 render() 的调用 - 它非常重要才能使其正常工作!在正常的执行流程中,base View 将首先被评估,然后是内部。为了在渲染基础之前调用set_global,您必须先明确渲染内部。


旁白:如果您正在做任何重要的模板工作,您真的应该考虑将 Kostache 与适当的“ViewModel”类一起使用,这是解决此问题的一种更优雅的方法。

关于php - Kohana 中的全局 View 变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20220106/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com