用velocity 将字符串中的"\n"换行符转变成<br/>现在非常常用下面提供两种解决方案
如果用如下方法经过测试不能够正常工作
#set($comments = $stringUtils.replace($comments, "\n", "<br />"))
但是如果采用jdk1.4中的 String.replaceAll(new, old) 可以解决
解决方案1:
#set($comments = $comments.replaceAll("\n", "<br />)
解决方法2:如上所提到的失败的方法,可以采用以下解决方案在velocity中添加如下方法
public void testCommonsStringUtils() throws Exception {
VelocityEngine engine = new VelocityEngine();
engine.init();
VelocityContext ctx = new VelocityContext();
ctx.put("stringUtils", new StringUtils());
ctx.put("comments", "this is a \n newline test");
ctx.put("newline", "\n");
ctx.put("break", "<br />");
String template = "#set($comments = $stringUtils.replace($comments,$newline,$break))";
template += "$comments";
StringWriter writer = new StringWriter();
engine.evaluate(ctx, writer, "", template);
assertEquals("this is a <br /> newline test", writer.toString());
}
veloctiy 初学,欢迎指正
如果用如下方法经过测试不能够正常工作
#set($comments = $stringUtils.replace($comments, "\n", "<br />"))
但是如果采用jdk1.4中的 String.replaceAll(new, old) 可以解决
解决方案1:
#set($comments = $comments.replaceAll("\n", "<br />)
解决方法2:如上所提到的失败的方法,可以采用以下解决方案在velocity中添加如下方法
public void testCommonsStringUtils() throws Exception {
VelocityEngine engine = new VelocityEngine();
engine.init();
VelocityContext ctx = new VelocityContext();
ctx.put("stringUtils", new StringUtils());
ctx.put("comments", "this is a \n newline test");
ctx.put("newline", "\n");
ctx.put("break", "<br />");
String template = "#set($comments = $stringUtils.replace($comments,$newline,$break))";
template += "$comments";
StringWriter writer = new StringWriter();
engine.evaluate(ctx, writer, "", template);
assertEquals("this is a <br /> newline test", writer.toString());
}
veloctiy 初学,欢迎指正
本文介绍如何使用Velocity模板引擎将字符串中的'
'换行符转换为HTML的<br/>标签,提供了两种解决方案并附带了示例代码。
533

被折叠的 条评论
为什么被折叠?



