首页 > 如何优雅地去掉 Velocity 模板输出的空白符?

如何优雅地去掉 Velocity 模板输出的空白符?

公司项目使用 Velocity 作为模板引擎,它有个致命的问题——在输出的 HTML 页面中会产生与开发时一致的空白符(空格、缩进、换行符等)

影响性能什么的不说,它会影响页面布局的呈现!如——

<div class="ws">
    <div>Block</div>
    <div>Block</div>
</div>
.ws div {
    display: inline-block;
    background-color: red;
}

代码运行后在两个元素中间会看到明显的间距,这不是所期望的!

网上搜过,说的都是在开发时源码上的处理,这实在是太不过优雅!有什么在渲染阶段而非编码阶段进行处理的优雅方式吗?


我用velocity从来没遇到你说的这种情况,你的html代码是写在模板文件里,跟velocity有毛关系。先学好基础再来谈论优雅行吗?


先读出velocity模板内容,然后用正则表达式把#if #else等标签前面的空格去除,然后封装成一个VelocityUtil公共类来处理,该处理算不上非常优雅,但是能够满足需求。


public static String parse(String template, String key, Object parameters) throws Exception{
    StringWriter writer = null;
    try{
        VelocityEngine ve = new VelocityEngine();
        ve.init();
        // 取得velocity的上下文context
        VelocityContext context = new VelocityContext();
        // 把数据填入上下文
        context.put(key, parameters);
        // 输出流
        writer = new StringWriter();
        // 转换输出, 去除velocity代码缩进的空格符
        ve.evaluate(context, writer, "", template.replaceAll("[ ]*(#if|#else|#elseif|#end|#set|#foreach)", "$1"));
        return writer.toString();
    }catch (Exception e){
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        throw e;
    }finally{
        close(writer);
    }
【热门文章】
【热门文章】