MustacheLayout.php
3.21 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
<?php
/**
* Created by PhpStorm.
* User: Hbomb
* Date: 15-3-12
* Time: 20:10
*/
namespace Plugin;
use Yaf\Application;
use Yaf\Dispatcher;
use Mustache;
class MustacheLayout extends Layout
{
protected $config = null;
public function __construct()
{
$this->config = Application::app()->getConfig()->get('application');
$this->layout = $this->config->layout->default;//默认布局名称是layout
$this->layout_path = $this->config->layout->path;//系统默认布局路径
}
/**
* 设置视图路径
*/
public function setScriptPath($path)
{
if (is_readable($path)) {
$this->tpl_dir = $path;
$this->layout_path = $path . "/../layouts";
return true;
}
throw new \Exception("Invalid path: {$path}");
}
/**
* 获取视图路径
*/
public function getScriptPath()
{
return $this->tpl_dir;
}
public function __isset($name)
{
return (null !== $this->tpl_vars[$name]);
}
public function __unset($name)
{
unset($this->tpl_vars[$name]);
}
/**
* 分配视图传参
*/
public function assign($name, $value = null)
{
$this->tpl_vars[$name] = $value;
}
public function assignRef($name, &$value)
{
$this->tpl_vars[$name] = $value;
}
/**
* 清除视图传参
*/
public function clearVars($name)
{
if (empty($name)) {
$this->tpl_vars[$name] = array();
}
$this->tpl_vars = array();
}
/**
* 渲染视图
*/
public function render($tpl, $tpl_vars = array())
{
$tpl_vars = array_merge($this->tpl_vars, $tpl_vars);
$dispatcher = Dispatcher::getInstance();
$module = $dispatcher->getRequest()->module;
$module_dir = $this->config->directory . '/modules/';//所在模块
$ext = array('extension' => $this->config->view->ext);//视图扩展名
if (!$this->tpl_dir)//如果没有设置视图目录的,默认当前模块的目录
{
$this->tpl_dir = $module_dir . $module . '/views';
}
$viewLoader = new Mustache\Loader\FilesystemLoader($this->tpl_dir, $ext);//设置视图目录
$partialsLoader = new Mustache\Loader\FilesystemLoader($this->tpl_dir . '/partials', $ext);//设置视图片段目录
$layoutLoader = new Mustache\Loader\FilesystemLoader($this->layout_path, $ext);//设置布局目录
//模板引擎初始化
$m = new Mustache\Engine(array(
'loader' => $viewLoader,
'partials_loader' => $partialsLoader,
));
$this->content = $m->render($tpl, $tpl_vars);//视图内容渲染
if (null == $this->layout) //如果没有布局,直接返回视图内容
{
return $this->content;
}
$tpl_vars['content'] = $this->content;//设置视图内容
$m->setLoader($layoutLoader);//设置布局视图的路径
return $m->render($this->layout, $tpl_vars);//和布局合成渲染html
}
/**
* 显示视图
*/
public function display($tpl, $tpl_vars = array())
{
echo $this->render($tpl, $tpl_vars);
}
}