2013-05-17 155 views
1

我是Kohana Framework的新手。我有一个问题 - 我如何将变量$title从Layout.php传递给Head.php?在php页面之间传递变量

在控制器:

<?php defined('SYSPATH') or die('No direct script access.'); 

class Controller_Admin_Quanly extends Controller_Template { 
    public $template='admin/layout'; 
    function _showWithTemplate($subview,$title) 
    { 
     $admin_path = 'admin/'; 
     $this->template->head = View::Factory(''.$admin_path.'head'); 
     $this->template->subview = View::Factory(''.$admin_path.''.$subview.''); 
     $this->template->title = $title; 
    } 
    public function action_index() 
    { 
     $this->_showWithTemplate('subview/home','Trang quản trị hệ thống'); 
    } 
} 

鉴于layout.php中:

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd"> 
<html xmlns="http://www.w3.org/1999/xhtml"> 
<head> 
    <?php echo $head?> 
</head> 
<body> 

</body> 
</html> 

鉴于Head.php:

<meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> 
<title><?=$title?></title> 
<base href="<?=URL::base()?>"> 
<link rel="stylesheet" type="text/css" href="style.css" /> 
<script type="text/javascript" src="javascript/jquery.min.js"></script> 
<script type="text/javascript" src="javascript/ddaccordion.js"></script> 

回答

1

你可以做这样的事情:

$admin_path = 'admin/'; 
$this->template->head = View::Factory(''.$admin_path.'head'); 
$this->template->head->title = $title; 

$this->template->subview = View::Factory(''.$admin_path.''.$subview.''); 
$this->template->title = $title; 

请注意$this->template->head->title = $title;您需要手动将它传递到头部视图。

0

你所寻找的是set_global

http://docs.kohanaphp.com/core/view#set_global

它可以让你设置一个变量为您的所有意见,能够使用。你不会通过它说,但它仍然会做你想做的。

例修复

function _showWithTemplate($subview,$title) 
{ 
    $admin_path = 'admin/'; 
    $this->template->head = View::Factory(''.$admin_path.'head'); 
    $this->template->subview = View::Factory(''.$admin_path.''.$subview.''); 
    $this->template->set_global('title', $title); 
} 
+0

这是一个坏主意。总是要避免全局。更甚的是,如果它被称为'title' – RJD22

+0

我知道这已经有一段时间了,但这不是设置全局变量。这会设置一个局部变量,Kohana会将它传递给它在当前视图中遇到的所有视图。这是递归完成的。再次,它不是一个全局变量,Kohana就是这么称呼它的。 – paquettg

+0

这应该像一个威胁。您的所有观点将被该价值覆盖。你应该总是避免它们,因为它们会产生意想不到的行为为两个视图独立设置变量是一个更好的解决方案,而不是将其视为全局视图。 – RJD22