Yii2压缩PHP中模板代码的输出问题
在Web开发中,无论是PHP的框架还是Python的框架,都会遇到使用模板的时候,在使用模板的时候就会遇到一个问题,就是使用模板编写的代码通过查看源代码的时候,会发现代码混乱不堪,对于代码格式又嫉妒追求的我来说我因受不了,但是目前也没有找到什么好的格式化输出的办法 但是格式化输出的话,也会需要处理一个压缩的问题,最终还是选择一个方案,开发的时候为了查看代码修改代码,就不做处理,但是上线的时候还是要做下压缩的处理,就是将无用的空格或者换行之类的全部删除掉。 问题前提已经抛出,现在看看如何解决这个问题,为了防止重复早轮子网上也查了一遍,结果也找到了,但是用composer安装的时候又是各种的不兼容,于是看了下源代码,其实很简单。这里我就简答的说下如何使用 具体的逻辑我就不多说了,其实自己理解了下面的使用流程,自己改写也不是太难的事情 第一步 功能开发创建两个文件一个是components/HtmlMinify.php,代码逻辑如下 view->on(View::EVENT_END_PAGE, [$this, 'onEventEndPage']); Yii::$app->response->on(Response::EVENT_BEFORE_SEND, [$this, 'onEventBeforeSend']); } public function onEventEndPage(Event $event) { $view = $event->sender; if ($this->css && !empty($view->css)) { foreach ($view->css as &$css) { $css = HtmlMinifyHelper::css($css); } } if ($this->js && !empty($view->js)) { foreach ($view->js as &$list) { foreach ($list as &$js) { $js = HtmlMinifyHelper::js($js); } } } } public function onEventBeforeSend(Event $event) { $response = $event->sender; if ($this->html & in_array($response->format, $this->formats)) { if (!empty($response->data)) { $response->data = HtmlMinifyHelper::html($response->data); } if (!empty($response->content)) { $response->content = HtmlMinifyHelper::html($response->content); } } } } 另外一个文件上是helpers/HtmlMinifyHelper.php,代码逻辑如下 !]+)(?:s+([^<>]*?)s*|s*)(/?)>#s', function ($matches) { return '<' . $matches[1] . preg_replace('#([^s=]+)(=([&;"]?)(.*?)3)?(s+|$)#s', ' $1$2', $matches[2]) . $matches[3] . '>'; }, str_replace("r", "", $input)); // Minify inline CSS declaration(s) if (strpos($input, ' style=') !==false){ $input=preg_replace_callback('#<([^<]+?)s+style=([&;"])(.*?)2(?=[/s>])#s',function ($matches){return '<' . $matches[1] . ' style=' . $matches[2] . self::css($matches[3]) . $matches[2]; }, $input); } return preg_replace( [ // t = text // o = tag open // c = tag close // Keep important white-space(s) after self-closing HTML tag(s) '#<(img|input)(>| .*?>)#s', // Remove a line break and two or more white-space(s) between tag(s) '#()|(>)(?:n*|s{2,})(<)|^s*|s*$#s', '#()|(?)s+()|(<[^/]*?>)s+(?!<)#s', // t+c || o+t '#()|(<[^/]*?>)s+(<[^/]*?>)|()s+()#s', // o+o || c+c '#()|()s+(s)(?!<)|(?)s+(s)(<[^/]*?/?>)|(<[^/]*?/?>)s+(s)(?!<)#s', // c+t || t+o || o+t -- separated by long white-space(s) '#()|(<[^/]*?>)s+()#s', // empty tag '#<(img|input)(>| .*?>)1>#s', // reset previous fix '#( ) (?![ 第二步 功能配置修改配置文件文件,这里修改config/web.php [ 'class' => 'appcomponentsHtmlMinify', 'html' => !YII_ENV_DEV, // 这里只开启了html的 ], 在bootstrap中加入如下代码 'bootstrap' => ['log', 'htmlMinify'], // log是默认加的, htmlMinify是我们自己加的 到这里就结束了配置可以试着在生产环境试下 总结以上所述是小编给大家介绍的Yii2压缩PHP中模板代码的输出问题,希望对大家有所帮助,在此也非常感谢大家对编程之家网站的支持! (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |