Velocity模板引擎#set在#foreach中無法賦值null問題

在使用Velocity模板引擎作爲Web應用頁面渲染引擎,經常會遇到由於Velocity語法不夠強大,導致莫名其妙問題。


比如在#foreach無法break。特別隱藏的問題是#foreach中使用#set無法清空臨時set對象。

<span style="font-family:Microsoft YaHei;font-size:12px;">#foreach($item in $!itemList)
	#set($xp = $!itemPriceMap.get($!{item.id}))
	// ...			
#end</span>

如上代碼中,如果itemPriceMap中不包含循環中的item,$xp在循環中還會保持上次循環的值。

所以一個引用被創建後,一般無法移除。


解決方案:

If the RHS is a property or method reference that evaluates to null, 
it will not be assigned to the LHS. Depending on how Velocity is configured, 
it is usually not possible to remove an existing reference from the 
context via this mechanism. (Note that this can be permitted by changing 
one of the Velocity configuration properties). 

在velocity.properties里加入directive.set.null.allowed = true。

<service name="VelocityService" class="com.xxx.DefaultVelocityService" earlyInit="true">
	<property name="input.encoding" value="GBK"/>
    <property name="parser.pool.size" value="100"/>
	<property name="directive.set.null.allowed" value="true"/>
	.......
</service>


發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章