smarty模板文件去回车和空行,让文件变的小一点

smarty是一款优秀的模板引擎,不仅可以自定义方法,还要以进行页面编译缓存,功能相当完美。

之前同事,问我smarty里模板文件可不可以把模板源文件去除一些没必要的空格和回车了。

请看下面的说明,这里用的是smarty2和smarty3

1、首先加个方法 striphtml方法

在smarty.class.php里添加一个去除多余空格回车的方法

/**
 * strip Html
 *
 * @param string $html
 * @return string
 */

    function striphtml($html)
	{
    	//return $html;
    	//strip php inline comment
    	$html = preg_replace(':\s+//.*?\n:', '', $html);
    
    	//strip html comments(消去html注释内容)
    	$html = preg_replace('/<!--\s*[^[][^!][^<].*?-->/s', '', $html);
    
    	//strip javascript comments(消去javascript注释内容)
    	$html = preg_replace('/\/\*.*?\*\//s', '', $html);
    
    	//strip blank between tags(消去相邻标记间空白)
    	$html = preg_replace('/>\s*</s', '><', $html);
    
    	//strip blank line(消去空行)
    	$html = preg_replace('/(\s)+/s', ' ', $html);
    
    	return trim($html);
    }

2、找到编译模板的方法smarty2中,_compile_resource

在文件smarty.class.php,方法是_compile_resource添加striphmtl

大约在文件的1432行,方法名是:_compile_resource

function _compile_resource($resource_name, $compile_path)
    {

        $_params = array('resource_name' => $resource_name);
        if (!$this->_fetch_resource_info($_params)) {
            return false;
        }

        $_source_content = $this->striphtml($_params['source_content']);
		....省略
		
}

3、找到编译模板的方法smarty3中,/smarty3/libs/sysplugins/smarty_template_source.php

在这个文件里,同样添加striphtml方法,然后再找到getContent()方法即可~

/**
     * Get source content
     *
     * @return string
     */
    public function getContent()
    {
        return isset($this->content) ? $this->striphtml($this->content) : $this->striphtml($this->handler->getContent($this));
    }

 

 

 

用浏览器访问站点的URL,查看查看源文件看看。

注意:

如果模板文件里有js等脚本,一定要严格输写,要花括号的地方一定要加、要分号的地方一定要加。

不然全变成一行会出错的~

 

 

转载于:https://my.oschina.net/lockupme/blog/666395

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值