我正在尝试将动态生成的文本括在Velocity模板中的引号中。动态生成的文本也可以为空,因此无需显示引号。但如果文本不为空,则需要用引号括起来。
使用Velocity模板可以实现这一点吗?当文本为空时,它周围的引号会消失吗?
我的代码如下:
#if ($messageFromSender == "") <i></i>
#else <i>"$!{messageFromSender}"</i>
这是我得到的例外:
org.apache.velocity.exception.ParseErrorException: Encountered "<EOF>"
提前致谢。
答案 0 :(得分:0)
您可以使用if语句检查文本值并做出相应的响应。
#if ($foo == "")
<h1>" "</h1>
#elseif ($foo != "")
<h1>"$foo"</h1>
答案 1 :(得分:0)
让我们假设您有一个列表itemList
,其中包含引号中的文字。
List<String> itemList = new ArrayList<>();
itemList.add("\"item1\""); //item1 in quotes
itemList.add("\"\""); //no text, just quotes
itemList.add("\"item2\""); //item2 in quotes
现在,将此itemList添加到velocity上下文中,也将StringUtils对象添加到上下文中。
context.put("itemList", itemList);
context.put("stringUtils", new org.apache.commons.lang.StringUtils());
现在,在力度模板中,您可以将文本显示为 -
#foreach($item in $itemList)
#if($stringUtils.length($item) > 2)
$item //print item if text is not empty
#else
//print nothing if text is empty.
#end
#end
length()
类的 StringUtils
方法用于检查项目的大小。
如果文本不为空,则大小将大于2.(引号大小+文本大小)。
如果文本为空,则其大小正好为2(引号大小)。
&#34; ITEM1&#34; //如果文本不为空,则打印项目。
//如果文本为空,则不打印任何内容。
&#34; ITEM2&#34; //如果文本不为空,则打印项目。
希望它有所帮助!让我知道任何澄清。