java - 如何优雅地去掉 Velocity 模板输出的空白符?
怪我咯
怪我咯 2017-04-17 15:48:37
0
2
594

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

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

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

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

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

怪我咯
怪我咯

走同样的路,发现不同的人生

reply all(2)
Peter_Zhu

First read the velocity template content, then use regular expressions to remove the spaces in front of labels such as #if #else, etc., and then encapsulate it into a VelocityUtil public class for processing. This processing is not very elegant, but it can meet the needs.


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)", ""));
        return writer.toString();
    }catch (Exception e){
        e.printStackTrace();
        logger.error(e.getMessage(), e);
        throw e;
    }finally{
        close(writer);
    }
迷茫

I have never encountered the situation you mentioned when using Velocity. Your HTML code is written in a template file, which has nothing to do with Velocity. Is it okay to learn the basics first and then talk about elegance?

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template