我如何通过Velocity修剪空白

时间:2011-12-21 17:43:13

标签: java whitespace velocity removing-whitespace

我有一个名为render_something的方法,它可以创建很多空格,例如:

<a href="#">#render_something('xxx')</a>

结果可能是:

<a href="#">     

           something that generate from redner_something


              </a> 

实际上我希望它是这样的:

<a href="#">something that generate from redner_something</a>

速度有这样的东西吗?

#trim(#render_something('xxx'))

8 个答案:

答案 0 :(得分:12)

我刚刚在Velocity Whitespace Gobbling上阅读了这篇文章,其中提出了一些解决方法,包括Velocity Whitespace Truncated By Line Comment

这基本上建议通过在每行末尾添加注释来注释掉换行符。它还建议不要缩进宏中的代码,以防止出现多余的(我最喜欢的单词之一)空格。

TBH这不是一个很好的解决方案,但可能适合您的需求。只需将##放在宏中每一行的末尾,这会使事情变得更好......等等

答案 1 :(得分:7)

似乎只有java native trim()可以工作。

$someValue.trim()适合我

答案 2 :(得分:2)

解决方案

在创建VelocityEngine的类中,添加如下方法

public String trim(String str) {
    return str.trim()/*.replace("\n", "").replace("\r", "")*/;
}

然后将以下内容添加到您创建的VelocityContext中:

    context.put("trimmer", this);

最后在速度模板中执行以下操作

<a href="#">$trimmer.trim("#render_something('xxx')")</a>

为什么会起作用?

尽管Velocity的行为已明确定义,但有时候看它的工作方式可能有点棘手。需要单独的trim() - 方法来将模板中的char序列转换为Java方法,您可以在其中调用String上的实际trim()。据我所知,Velocity内部没有修剪,但你总是可以用这样的技巧回调Java。

双引号是必要的,因为#render_something只是一个宏,而不是一个函数调用,这意味着宏中的语句结果逐字地放到宏被“执行”的位置。

答案 3 :(得分:2)

我挣扎了一段时间才找到一个直接解决空白吞噬的方法,所以在这里我最终提出了一个。它的灵感来源于Vadzim的答案和本页http://wiki.apache.org/velocity/StructuredGlobbingResourceLoader

我们可以在网站上找到的StructuredGlobbingResourceLoader有一个复杂的行为,并没有摆脱任何类型的空白,所以我修改它以获得简单的行为:“删除行的开头的任何空格,并添加每行末尾的注释“(这会阻止换行评估)。过滤器在加载时应用于输入流。

这种速度模板

#if($value)
    the value is $value
#end

转换为

#if($value)##
the value is $value##
#end##

然后,如果你想要换行或开头行空格,你必须把($ br,“\ n”)和put($ sp,“”)放在你的上下文中,就像Vadzim所解释的那样并明确地使用它们在你的模板中。这种做法将允许您保持缩进模板,并具有最大程度的控制。

从此页面获取课程http://wiki.apache.org/velocity/StructuredGlobbingResourceLoader 将扩展类更改为您需要的加载器类型(这个使用webapp加载器) 用我提供的代码替换read()方法 在您的属性中使用该类作为资源加载器。 webapp loader的示例:webapp.resource.loader.class = ... StructuredGlobbingResourceLoader

public int read() throws IOException {        
    int ch;
    switch(state){
        case bol: //beginning of line, read until non-indentation character
            while(true){
                ch = in.read();
                if (ch!=(int)' ' && ch!=(int)'\t'){
                    state = State.content;
                    return processChar(ch);
                }
            }

        case content:
            ch = in.read();
            return processChar(ch);

        //eol states replace all "\n" by "##\n"
        case eol1: 
            state = State.eol2;
            return (int)'#';

        case eol2:
            state = State.bol;
            return (int)'\n';

        case eof: 
            return -1;
    }
    return -1;
}

//Return the normal character if not end of file or \n
private int processChar(int ch){
    switch(ch){
    case -1:
        state = State.eof;
        return -1;
    case (int)'\n':
        state = State.eol1;
    return (int)'#';
    default:
        return ch;
    }
}

欢迎任何关于我的实施的反馈

答案 4 :(得分:1)

以下是velocity whitespace gobbling的替代解决方案,允许使用Tab键模板结构。

在自定义ResourceLoader首次加载时预处理每个模板文本:

private String enhanceTemplate(String body) {
    if (!body.startsWith("##preserveWhitespace")) {
        body = body.replaceAll("(##.*)?[ \\t\\r]*\\n+[ \\t\\r]*", Matcher.quoteReplacement("##\n"));
        body = body.trim();
    }
    return body;
}

这只用一个commented newline替换所有新行和调整空格。

可以使用默认上下文中的$ br和$ sp变量显式插入换行符和尾部空格:

private static final VelocityContext DEFAULT_CONTEXT = new VelocityContext(new HashMap<String, String>() {{
    put("sp", " ");
    put("br", "\n");
}});

答案 5 :(得分:1)

在某些情况下,我必须像js或css一样最小化我的脚本。它运作良好,但人类阅读并不容易。只是另一种消除多余空间的选择:

<ul class="tabs">#foreach($par in $bodypars)#set( $parLen = ${_MathTool.toInteger($bodypars.size())} )#set( $parLn = $parLen - 1 )#set( $thClass = 'tb'+${parLn} )#set( $thaClass = '' )#if( $foreach.index == 1 )#set( $thClass = ${thClass}+' selected' )#set( $thaClass = ' selected' )#end#if($foreach.index != 0 && $parLen <= $maxTabs)#set ( $btitle = $_XPathTool.selectSingleNode($par,'item-subtitle') )<li class="${thClass}">#if($!btitle && $btitle != '')<a href="#" class="#cleanString($btitle.value.toLowerCase())${thaClass}">$_SerializerTool.serialize($btitle, true)</a>#end</li>#end#end</ul>

答案 6 :(得分:0)

Velocity Whitespace Truncated By Line Comment的启发,可以使用块注释而不是行注释来获得更好的效果:

#foreach( $record in $records )#**
    *##if( $record.id == 0 )#**
    *##end
#end

突出显示适当的语法,注释不是很引人注目。

答案 7 :(得分:0)

您可以使用标准的Java修剪,如果是对象而不是字符串,请注意变量。

$string.trim()  //work fine
$object.trim()  //exception

祝你有美好的一天!