thinkphp5.1 - twig模板-全局变量

thinkphp5.1 - twig模板-全局变量
我们在定义 ccs 之类的静态文件的时候,经常会使用
<link rel="stylesheet" href="__ROOT__/static/css/bootstrap.css" />
定义个__ROOT__变量,然后全局替换调

1、如果使用默认模板,那直接在
自定义变量要去 config里的template.php 设置 假设你要 __ROOT__,
'tpl_replace_string' => [
'__ROOT__'=>'/static',
]
这样就引到 public/static 目录了

2、但是如果要使用 twig 模板引擎就不行了,那 twig 怎么处理呢
twig本身提供了addGlobal函数处理全局变量,我们看thinkphp的扩展
twig 的Twig.php中有个配置
// 模板引擎参数
protected $config = [
'view_base' => '',
// 模板起始路径
'view_path' => '',
// 模板文件后缀
'view_suffix' => 'twig',
// 模板文件名分隔符
'view_depr' => '/',
'cache_path' => '',
'strict_variables' => true,
'auto_add_function' => false,
'functions' => [],
'filters' => [],
'globals' => [],
'runtime' => []
];

然后看代码发现:
if (!empty($this->config['globals'])) {
foreach ($this->config['globals'] as $name => $global) {
$twig->addGlobal($name, $global);
}
},

所以我们只需要配置这个字段就行了,我们不需要在Twig.php中配置,这里的配置会和
config/template.php目录中的配置合并,而且config/template.php的配置优先,所以我们只需要
在config/template.php中配置,类似于这样
'globals'=>[
'__STATIC__'=>'/static'
]
就可以了。
3、然后我们在模板文件中怎么使用呢?
<link rel="stylesheet" type="text/css" href="{{ __STATIC__ }}/navigation.css" />

 

posted on 2019-04-18 12:48  ZhYQ_note  阅读(1326)  评论(0编辑  收藏  举报

导航