我使用Velocity 1.7来格式化字符串,并且我在使用默认值时遇到了一些麻烦。 Velocity本身在没有设置值的情况下没有特殊的语法,我们想使用另一个默认值。 通过速度的手段,它看起来像:DisplayTool的安装和使用
#if(!${name})Default John#else${name}#end
这是unconveniant我的情况。 google搜索,我发现DisplayTool,根据文件它看起来像后:
$display.alt($name,"Default John")
所以我添加的Maven的依赖,但不知道如何DisplayTool添加到我的方法,它是很难找到此说明。 也许有人可以建议帮助或提供有用的链接..
我的方法:
public String testVelocity(String url) throws Exception{
Velocity.init();
VelocityContext context = getVelocityContext();//gets simple VelocityContext object
Writer out = new StringWriter();
Velocity.evaluate(context, out, "testing", url);
logger.info("got first results "+out);
return out.toString();
}
当我送
String url = "http://www.test.com?withDefault=$display.alt(\"not null\",\"exampleDefaults\")&truncate=$display.truncate(\"This is a long string.\", 10)";
String result = testVelocity(url);
我得到“http://www.test.com ?withDefault = $ display.alt(\“not null \”,\“exampleDefaults \”)& truncate = $ display.truncate(\“This is a long string。\”,10)“without changes,but should get
"http://www.test.com?withDefault=not null&truncate=This is...
请告诉我我错过了什么。谢谢。
谢谢,但我正在寻找一些东西给我方便的工具来格式化字符串,而不使用模板。并且,当收到字符串时,我不知道确切位置将在什么位置引用以及它的默认值是什么。一切都应该通过特殊表达来设置。我认为显示工具提供了这个功能。可惜它没有。不管怎样,谢谢你。 – me1111
@ me1111查看Apache Commons Lang中的[StringUtils](http://commons.apache.org/lang/StringUtils.html)类,特别是'defaultString '和'defaultEmpty'方法。 –
谢谢,但如果我将使用java的标准方法,那么没有理由使用Velocity。我被告知研究什么更快,更舒适。找到另一个我认为可以代替Velocity - Freemarker的工具,默认情况下,它具有像unsafe_expr!default_expr一样的优势。感谢您的时间。 – me1111