{hook} 钩子函数
{hook} 钩子函数 定义和 {function} 类似,主要使用场景是将模板解析中的函数以匿名函数方式获取,并提供给PHP 进行调用的函数。
在一些场景下面,我们可能不需要对渲染的模板进行输出,而是需要模板引擎为我们生成一些待用的函数,在我们需要的时候执行,那么可以使用钩子函数来实现这个目的。
使用例子如下:
hook.tpl
{hook fn=link item=[]}<a href="/{$item.id}.html">{$item.name}</a>{/hook}
{hook fn=state state=0}{if $state ==1}备货中{elseif $state ==2}已备货{elseif $state ==3}已发货{elseif $state==4}已收货{else}未知状态{/if}{/hook}
php 代码:
define('ROOT_DIR', __DIR__);
date_default_timezone_set('PRC');
require(ROOT_DIR . '/vendor/autoload.php');
use sdopx\Sdopx;
$sdopx = new Sdopx();
$sdopx->setTemplateDir('./view');
$sdopx->setCompileDir('./runtime');
$list = [
['id' => 1, 'name' => 'wj001', 'state' => 1],
['id' => 2, 'name' => 'wj001', 'state' => 2],
['id' => 3, 'name' => 'wj001', 'state' => 2],
['id' => 4, 'name' => 'wj001', 'state' => 3],
['id' => 5, 'name' => 'wj001', 'state' => 4],
];
$sdopx->fetch('hook.tpl');
//获取钩子函数
$funLink = $sdopx->getHook('link');
$funState = $sdopx->getHook('state');
foreach ($list as &$item) {
if ($funLink !== null) {
$item['link'] = $funLink(['item' => $item]);
}
if ($funState !== null) {
$item['stateText'] = $funState(['state' => $item['state']]);
}
}
print_r($list);
最后打印:
Array
(
[0] => Array
(
[id] => 1
[name] => wj001
[state] => 1
[link] => <a href="/1.html">wj001</a>
[stateText] => 备货中
)
[1] => Array
(
[id] => 2
[name] => wj001
[state] => 2
[link] => <a href="/2.html">wj001</a>
[stateText] => 已备货
)
[2] => Array
(
[id] => 3
[name] => wj001
[state] => 2
[link] => <a href="/3.html">wj001</a>
[stateText] => 已备货
)
[3] => Array
(
[id] => 4
[name] => wj001
[state] => 3
[link] => <a href="/4.html">wj001</a>
[stateText] => 已发货
)
[4] => Array
(
[id] => 5
[name] => wj001
[state] => 4
[link] => <a href="/5.html">wj001</a>
[stateText] => 已收货
)
)