-
-
Notifications
You must be signed in to change notification settings - Fork 3
/
mfwTemplate.php
130 lines (106 loc) · 2.62 KB
/
mfwTemplate.php
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
130
<?php
class mfwTemplate
{
public static $curobj; ///< 現在処理中のTemplate (Template用関数で使用)
protected $templatefile;
protected $layoutfile;
protected $blockdir;
protected $params;
/**
* @param[in] name テンプレート名
* @param[in] basedir テンプレート、ブロックのベースディレクトリ
*/
public function __construct($name,$basedir='/data')
{
$this->templatedir = APP_ROOT."{$basedir}/templates";
$this->blockdir = APP_ROOT."{$basedir}/blocks";
$file = "{$this->templatedir}/{$name}.php";
if(!file_exists($file)){
throw new InvalidArgumentException("template file is not exists: {$file}");
}
$this->templatefile = $file;
// default layout file (optional)
$this->layout = "{$this->templatedir}/_layout.php";
}
/**
* レイアウトファイルの差し替え.
*/
public function setLayout($layout)
{
$file = "{$this->templatedir}/{$layout}.php";
if(!file_exists($file)){
throw new InvalidArgumentException("layout file is not exists: {$file}");
}
$this->layout = $file;
}
/**
* ページ構築.
*/
public function build($params=array())
{
$template = file_get_contents($this->templatefile);
// blockからの呼び出し用に保存
self::$curobj = $this;
$this->params = $params;
$r = new mfwTemplateRenderer($template,$params);
$contents = $r->render();
if($this->layout && file_exists($this->layout)){
$layout = file_get_contents($this->layout);
$this->params['contents'] = $contents;
$r = new mfwTemplateRenderer($layout,$this->params);
$contents = $r->render();
}
return $contents;
}
public function blockFileName($name)
{
return "{$this->blockdir}/{$name}.php";
}
public function getParams()
{
return $this->params;
}
}
/**
* レンダリングクラス.
* 変数を隔離するためこの中でextractする.
*/
class mfwTemplateRenderer
{
protected $template;
protected $params;
public function __construct($template,$params)
{
$this->template = $template;
$this->params = $params;
}
public function render()
{
extract($this->params);
ob_start();
eval('?>'.$this->template);
return ob_get_clean();
}
}
/**
* Template用関数: URL生成
*/
function url($query,$scheme=null)
{
return mfwRequest::makeUrl($query,$scheme);
}
/**
* Template用関数: ブロック読み込み
*/
function block($name,$additional_params=array())
{
$t = mfwTemplate::$curobj;
$file = $t->blockFileName($name);
if(!file_exists($file)){
return "block '{$name}' is not found.";
}
$r = new mfwTemplateRenderer(
file_get_contents($file),
$additional_params + $t->getParams());
return $r->render();
}