近期开发项目基本都用slim框架在开发,然后配合着twig框架作为模板引擎使用吧,这文档就着实让人头疼。twig内置的函数库有限,又没提及怎么扩展定义函数,无奈自行度娘(度娘上也少)。
下面是自定义函数的代码
use Twig\Environment;
use Twig\Loader\FilesystemLoader;
use Twig\TwigFunction;
$config = [
"templates_path"=>"", // 模板路径(静态页面)
"compilation_cache_path"=>"", // 缓存路径
"debug"=>true, // debug
];
$sayFunction = new TwigFunction("say_name","say");
$loader = new FilesystemLoader($config['templates_path']);
$this->twig = new Environment($loader,[
"cache"=>$config['compilation_cache_path'],
"debug"=>$config['debug'],
]);
$twig->addFunction($sayFunction);
function say($name){
return "this is {$name}";
}
使用方式:
<div>
这里是自定义函数输出:{{say_name('test')}}
</div>