feat: 增加var标签

This commit is contained in:
augushong
2025-03-05 20:29:32 +08:00
parent efe5062a84
commit 0f4c0e5747
2 changed files with 39 additions and 0 deletions

View File

@@ -45,6 +45,7 @@ class Cx extends Taglib
'notdefined' => ['attr' => 'name'],
'load' => ['attr' => 'file,href,type,value,basepath', 'close' => 0, 'alias' => ['import,css,js', 'type']],
'assign' => ['attr' => 'name,value', 'close' => 0],
'var' => ['attr' => 'name,value', 'close' => 0],
'define' => ['attr' => 'name,value', 'close' => 0],
'for' => ['attr' => 'start,end,name,comparison,step'],
'url' => ['attr' => 'link,vars,suffix,domain', 'close' => 0, 'expression' => true],
@@ -577,6 +578,33 @@ class Cx extends Taglib
return $parseStr;
}
/**
* 如果变量在当前上下文不存在则设置,否则不设置
*
* @param array $tag
* @param string $content
* @return string
*/
public function tagVar(array $tag, string $content): string
{
$name = $this->autoBuildVar($tag['name']);
if(!isset($tag['value'])) {
$value = 'null';
}else{
$flag = substr($tag['value'], 0, 1);
if ('$' == $flag || ':' == $flag) {
$value = $this->autoBuildVar($tag['value']);
} else {
$value = '\'' . $tag['value'] . '\'';
}
}
$parseStr = '<?php if(!isset('.$name.')) { ' . $name . ' = ' . $value . ' ;} ?>';
return $parseStr;
}
/**
* define标签解析
* 在模板中定义常量 支持变量赋值

View File

@@ -16,6 +16,7 @@ namespace think\view\driver;
use app\common\tools\PathTools;
use think\App;
use think\facade\Env;
use think\helper\Arr;
use think\helper\Str;
use think\Template;
use think\template\exception\TemplateNotFoundException;
@@ -39,6 +40,8 @@ class Think
'tpl_cache' => true,
];
public $data = [];
public function __construct(private App $app, array $config = [])
{
$this->config = array_merge($this->config, (array) $config);
@@ -78,6 +81,13 @@ class Think
return 'app(\'request\')->' . $method . '(' . $params . ')';
});
$this->template->extend('$View', function (array $vars) {
$params = implode('.', $vars);
return "'" . Arr::get($this->data, $params, '') . "'";
});
}
/**
@@ -112,6 +122,7 @@ class Think
if (!is_file($template)) {
throw new TemplateNotFoundException('template not exists:' . $template, $template);
}
$this->data = array_merge($this->data, $data);
return $this->template->fetch($template, $data);
}