在 Java 中的 Velocity 模板中为动态生成的文本加上引号
Putting quotes around dynamically generated text in Velocity Templates in Java
我试图在 Velocity 模板中用引号将动态生成的文本括起来。动态生成的文本也可以为空,因此不需要显示引号。但如果文本不为空,则需要用引号括起来。
这可以使用 Velocity 模板来实现吗?当文本为空时,周围的引号会消失?
我的代码如下:
#if ($messageFromSender == "") <i></i>
#else <i>"$!{messageFromSender}"</i>
这是我得到的异常:
org.apache.velocity.exception.ParseErrorException: Encountered "<EOF>"
提前致谢。
您可以使用 if 语句来检查文本值并做出相应的响应。
#if ($foo == "")
<h1>" "</h1>
#elseif ($foo != "")
<h1>"$foo"</h1>
是的,你可以做到。试试这个 -
假设您有一个列表 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
class 方法用于检查项目的大小。
如果文本不为空,则大小将大于 2。(引号大小 + 文本大小)。
如果文本为空,其大小将恰好为 2(引号的大小)。
输出
"item1" //如果文本不为空则打印项目。
//如果文本为空,则不打印。
"item2" //如果文本不为空则打印项目。
Hope it helped ! Let me know for any clarification.
我试图在 Velocity 模板中用引号将动态生成的文本括起来。动态生成的文本也可以为空,因此不需要显示引号。但如果文本不为空,则需要用引号括起来。
这可以使用 Velocity 模板来实现吗?当文本为空时,周围的引号会消失?
我的代码如下:
#if ($messageFromSender == "") <i></i>
#else <i>"$!{messageFromSender}"</i>
这是我得到的异常:
org.apache.velocity.exception.ParseErrorException: Encountered "<EOF>"
提前致谢。
您可以使用 if 语句来检查文本值并做出相应的响应。
#if ($foo == "")
<h1>" "</h1>
#elseif ($foo != "")
<h1>"$foo"</h1>
是的,你可以做到。试试这个 -
假设您有一个列表 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
class 方法用于检查项目的大小。
如果文本不为空,则大小将大于 2。(引号大小 + 文本大小)。
如果文本为空,其大小将恰好为 2(引号的大小)。
输出
"item1" //如果文本不为空则打印项目。
//如果文本为空,则不打印。
"item2" //如果文本不为空则打印项目。
Hope it helped ! Let me know for any clarification.