velocity中字符串拼接空格处理
实践:
代码:
京东支付##
#if($index > 1)
、
#end
#end
#if($textDisplay.indexOf("WXSYS")>=0)
微信##
#if($index > 2)
、
#end
#end
#if($textDisplay.indexOf("ZFB")>=0)
支付宝##
#if($index > 3)
、
#end
#end
扫一扫,向我付款
扫一扫,向我付款
拼接字符串中行首不能缩进
实际效果:
空格效果:
博客分类:
最近的项目采用Velocity 1.7作为模板引擎,几天用下来,感觉还是挺爽的。不过今天发现一个坑:macro里面如果有多行的话,输出的字符串前后都被加上了换行和空格。直接上代码:
Js代码
- #macro(getContextPath)
- #set($root = $context.webApplicationContext.servletContext.contextPath)
- #if($root.lastIndexOf('/') == 0)
- #set($root = $root + '/')
- #end
- $root
- #end
调用:
Js代码
- aa#{getContextPath}aa
输出:
Js代码
- aa /web/ aa
中间确实多了空格,我的目的是所有的URL前缀都加上这个context路径,比如:
Html代码
- <a href="#{getContextPath}menu/list">xxx</a>
最终我看到的结果会是这样:
Html代码
- <a href="# /web/ menu/list">xxx</a>
很明显这不符合我的要求。
网上搜了一把,终于在Velocity的WIKI搜到了解决方案,
http://wiki.apache.org/velocity/VelocityWhitespaceTruncatedByLineComment
第一种方案,把macro里面的所有语句写成一行(不要换行),在行的末尾加上
##
这种方案缺点很明显,程序完全不具备可读性。
第二种方案(
会英文的,上面的链接打开,拉到底部,那段就是解决方案
),直接上代码:
Js代码
- #macro(getContextPath)
- #set($root = $context.webApplicationContext.servletContext.contextPath)
- #if($root.lastIndexOf('/') == 0)
- #set($root = $root + '/')
- #end
- $root##
- #end
解释下:
行首不能缩进
,否则还是有空格;(这是去除字符串前面的空格和换行)
输出数据的行(上面$root是输出数据的)末尾需要加上
##
(这是去除字符串尾部的空格)
PS:上面的代码是获取Servlet的context路径。
本文出自ITEYE BLOG,转载请注明出处:http://qurey.iteye.com/blog/1944104