-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathcodeigniter-twig.php
93 lines (82 loc) · 2.08 KB
/
codeigniter-twig.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
<?php
// use composer
require FCPATH.'../vendor/autoload.php';
// use package
// require APPPATH.'third_party/Twig/lib/Twig/Autoloader.php';
class Twig
{
/**
* Twig Object
*/
private $_twig;
/**
* 构造方法
*/
public function __construct()
{
// Register Autoloader
Twig_Autoloader::register();
// twig filesystem
$loader = new Twig_Loader_Filesystem(APPPATH.'views');
// twig object
$twig = new Twig_Environment($loader, array(
'cache' => APPPATH.'cache',
'debug' => true,
'autoescape' => false,
'optimizations' => -1
));
// debug mode
$twig->addExtension(new Twig_Extension_Debug());
$this->_twig = $twig;
}
/**
* 渲染模板
*/
public function render($view, $data = array(), $return = false)
{
$view = $this->_twig->loadTemplate($view);
if( false === $return ) {
return $view->display($data);
}
return $view->render($data);
}
/**
* 添加全局变量
*/
public function addGlobal($key, $value = NULL)
{
if( is_array($key) ) {
foreach( $key AS $k=>$v ) {
$this->addGlobal($k, $v);
}
} else {
$this->_twig->addGlobal((string) $key, (string) $value);
}
}
/**
* 添加函数
*/
public function addFunction($function)
{
if( is_array($function) ) {
foreach( $function AS $v ) {
$this->addFunction($v);
}
} else {
$this->_twig->addFunction((string) $function, new Twig_Filter_Function((string) $function));
}
}
/**
* 添加过滤器
*/
public function addFilter($filter)
{
if( is_array($filter) ) {
foreach( $filter AS $v ) {
$this->addFilter($v);
}
} else {
$this->_twig->addFilter((string) $filter, new Twig_Filter_Function((string) $filter));
}
}
}