From 0f4c0e574705ead37aa6275733dce497bf8e88fc Mon Sep 17 00:00:00 2001 From: augushong Date: Wed, 5 Mar 2025 20:29:32 +0800 Subject: [PATCH] =?UTF-8?q?feat:=20=E5=A2=9E=E5=8A=A0var=E6=A0=87=E7=AD=BE?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- extend/think/template/taglib/Cx.php | 28 ++++++++++++++++++++++++++++ extend/think/view/driver/Think.php | 11 +++++++++++ 2 files changed, 39 insertions(+) diff --git a/extend/think/template/taglib/Cx.php b/extend/think/template/taglib/Cx.php index 01d7ddb..cbbfabe 100644 --- a/extend/think/template/taglib/Cx.php +++ b/extend/think/template/taglib/Cx.php @@ -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 = ''; + return $parseStr; + } + /** * define标签解析 * 在模板中定义常量 支持变量赋值 diff --git a/extend/think/view/driver/Think.php b/extend/think/view/driver/Think.php index b485801..5d71f84 100644 --- a/extend/think/view/driver/Think.php +++ b/extend/think/view/driver/Think.php @@ -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); }