struts2里有select标签,可以方便的生成html的select元素.
用velocity以后,怎么用select标签呢
第一,可以用#sselect.事实上,在velocity页面中,可以使用#s的前缀来使用struts2的标签
详情见[url]http://struts.apache.org/release/2.3.x/docs/velocity-tags.html[/url]
第二,用velocity的宏来实现自定义组件.
先考虑一个普通java类Bar,有foo和bar两个属性,在velocity中访问这两个属性,可以用
$bar.foo
$bar.bar
但是如何能动态指定要访问的属性呢?
evaluate指令可以用来在运行时动态解析模板语言.
#set($prop="bar")
#evaluate("\$bar.$prop")
#set($prop="foo")
#evaluate("\$bar.$prop")
其中"\"用来转义"$"
下面用宏来组成一个自定义的select元素
#macro (fooList $list $name $listKey $listValue $headerKey $headerValue)
#set($currentValueExpression = "$$name")
#set($currentValue = "#evaluate($currentValueExpression)")
<select name="$name">
#if( $headerKey && $headerValue )
<option value="$headerKey">$headerValue</option>
#end
#foreach( $v in $list )
#set($dynamicValueExpression = "\$v.$listValue")
#set($dynamicKeyExpression = "\$v.$listKey")
#set($dynamicKey = "#evaluate($dynamicKeyExpression)")
<option value="$dynamicKey"
#if( $dynamicKey == $currentValue )
selected="selected"
#end>
#evaluate($dynamicValueExpression)</option>
#end
</select>
#end
这样来调用这个宏,产生类似于struts2 select标签的效果
#fooList($barList "currentBarId" "fooId" "fooName")
最后吐槽下velocity的文档,它说调用宏的时候,传递的参数个数必须和定义时一致
[quote]
when the Velocimacro is invoked, it must be called with the same number of arguments with which it was defined
[/quote]
那现在如果我硬少几个参数,照样能调用,也不报错,那个"must"真是莫大的讽刺....
用velocity以后,怎么用select标签呢
第一,可以用#sselect.事实上,在velocity页面中,可以使用#s的前缀来使用struts2的标签
详情见[url]http://struts.apache.org/release/2.3.x/docs/velocity-tags.html[/url]
第二,用velocity的宏来实现自定义组件.
先考虑一个普通java类Bar,有foo和bar两个属性,在velocity中访问这两个属性,可以用
$bar.foo
$bar.bar
但是如何能动态指定要访问的属性呢?
evaluate指令可以用来在运行时动态解析模板语言.
#set($prop="bar")
#evaluate("\$bar.$prop")
#set($prop="foo")
#evaluate("\$bar.$prop")
其中"\"用来转义"$"
下面用宏来组成一个自定义的select元素
#macro (fooList $list $name $listKey $listValue $headerKey $headerValue)
#set($currentValueExpression = "$$name")
#set($currentValue = "#evaluate($currentValueExpression)")
<select name="$name">
#if( $headerKey && $headerValue )
<option value="$headerKey">$headerValue</option>
#end
#foreach( $v in $list )
#set($dynamicValueExpression = "\$v.$listValue")
#set($dynamicKeyExpression = "\$v.$listKey")
#set($dynamicKey = "#evaluate($dynamicKeyExpression)")
<option value="$dynamicKey"
#if( $dynamicKey == $currentValue )
selected="selected"
#end>
#evaluate($dynamicValueExpression)</option>
#end
</select>
#end
这样来调用这个宏,产生类似于struts2 select标签的效果
#fooList($barList "currentBarId" "fooId" "fooName")
最后吐槽下velocity的文档,它说调用宏的时候,传递的参数个数必须和定义时一致
[quote]
when the Velocimacro is invoked, it must be called with the same number of arguments with which it was defined
[/quote]
那现在如果我硬少几个参数,照样能调用,也不报错,那个"must"真是莫大的讽刺....