From 0313afdc20916403fd23182d8e50eb909ad4b8fa Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E5=88=98=E5=B0=8F=E6=99=8B=E5=95=A6?= <1540175452@qq.com> Date: Mon, 2 Nov 2020 10:29:34 +0800 Subject: [PATCH] Update Template.php MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit 解析特殊指令,如@json,使其在script标签中的代码格式化的时候不受影响 --- src/Template.php | 45 ++++++++++++++++++++++++++++++++++++++++++++- 1 file changed, 44 insertions(+), 1 deletion(-) diff --git a/src/Template.php b/src/Template.php index a94d14c..13aa0be 100644 --- a/src/Template.php +++ b/src/Template.php @@ -91,6 +91,13 @@ class Template * @var CacheInterface */ protected $cache; + + /** + * 扩展指令解析规则 + * + * @var array + */ + protected $directive = []; /** * 架构函数 @@ -210,6 +217,18 @@ public function extend(string $rule, callable $callback = null): void { $this->extend[$rule] = $callback; } + + /** + * 扩展模板指令解析规则 + * + * @access public + * @param string $rule 解析规则 + * @param callable|null $callback 解析规则 + * @return void + */ + public function directive(string $rule, callable $callback = null):void{ + $this->directive[$rule] = $callback; + } /** * 渲染模板文件 @@ -493,6 +512,9 @@ public function parse(string &$content): void // 解析普通模板标签 {$tagName} $this->parseTag($content); + + // 解析特殊指令 + // 还原被替换的Literal标签 $this->parseLiteral($content, true); @@ -962,6 +984,24 @@ private function parseTag(string &$content): void unset($matches); } + + // 解析特殊指令,如:@json() + $sRegex = $this->getRegex('@'); + if(preg_match_all($sRegex, $content, $matches, PREG_SET_ORDER)){ + foreach($matches as $match){ + $directive = stripslashes($match[1]); + + // 指令 + if(isset($this->directive[$directive])){ + $callback = $this->directive[$directive]; + $parseStr = $callback($match[2]); + + $content = str_replace($match[0], $parseStr, $content); + } + } + + unset($matches); + } } /** @@ -1269,7 +1309,10 @@ private function getRegex(string $tagName): string } else { $regex = $begin . '((?:[\$]{1,2}[a-wA-w_]|[\:\~][\$a-wA-w_]|[+]{2}[\$][a-wA-w_]|[-]{2}[\$][a-wA-w_]|\/[\*\/])(?>(?:(?!' . $end . ').)*))' . $end; } - } else { + } elseif('@' == $tagName){ + $regex = '\@([a-wA-w_]*)\(([\$a-wA-w_]*)\)'; + // $regex = '\@([a-wA-w_]*\([\$a-wA-w_]*\))'; + } else { $begin = $this->config['taglib_begin']; $end = $this->config['taglib_end']; $single = strlen(ltrim($begin, '\\')) == 1 && strlen(ltrim($end, '\\')) == 1 ? true : false;