---
title: "Velocity的坑——字符串首尾的空格那些事"
author: "cjm0000000"
date: "2013-09-18T21:16:03Z"
tags: []
categories: ["编程语言"]
slug: "velocity"
draft: false
lastmod: "2013-09-18T21:16:32Z"
id: 1944104
url: "https://qurey.iteye.com/blog/1944104"
---

最近的项目采用Velocity 1.7作为模板引擎，几天用下来，感觉还是挺爽的。不过今天发现一个坑：macro里面如果有多行的话，输出的字符串前后都被加上了换行和空格。直接上代码：

```
#macro(getContextPath)
    #set($root =  $context.webApplicationContext.servletContext.contextPath)
    #if($root.lastIndexOf('/') == 0)
        #set($root = $root + '/')
    #end
    $root
#end
```

 

调用：

```
aa#{getContextPath}aa
```

 输出：

```
aa /web/ aa
```

 中间确实多了空格，我的目的是所有的URL前缀都加上这个context路径，比如：

```
<a href="#{getContextPath}menu/list">xxx</a>
```

 最终我看到的结果会是这样：

```
<a href="#                   /web/ menu/list">xxx</a>
```

 很明显这不符合我的要求。

 

网上搜了一把，终于在Velocity的WIKI搜到了解决方案，[http://wiki.apache.org/velocity/VelocityWhitespaceTruncatedByLineComment](http://wiki.apache.org/velocity/VelocityWhitespaceTruncatedByLineComment)

 

第一种方案，把macro里面的所有语句写成一行（不要换行），在行的末尾加上**##**

这种方案缺点很明显，程序完全不具备可读性。

 

第二种方案（会英文的，上面的链接打开，拉到底部，那段就是解决方案），直接上代码：

 

```
#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