grails g:select标签使用List<Map<String,String>>作为from标签数据源
GSP页面中g:select用于创建一个HTML的selects标签.
下面例子里面用到的g:select属性有
from(必需)-select的范围
value(可选)-from范围内当前的选择值.
optionKey(可选)-用于指定生成的HTMLselects标签中<option>元素的value属性
optionValue(可选)-用于指定生成的HTMLselects标签中<option>元素显示内容
value(optional)-Thecurrentselectedvaluethatevaluatesequals()totrueforoneoftheelementsinthefromlist.
noSelection(optional)-Asingle-entryMapdetailingthekeyandvaluetouseforthe"noselectionmade"choiceintheselectbox.Ifthereisnocurrentselectionthiswillbeshownasitisfirstinthelist,andifsubmittedwiththisselected,thekeythatyouprovidewillbesubmitted.Typicallythiswillbeblank-butyoucanalsouse'null'inthecasethatyou'repassingtheIDofanobject
valueMessagePrefix(Optional)-BydefaultthevalueoftheoptionelementwillbetheresultofatoString()calloneachelementinthefromattributelist.Settingthisallowsthevaluetoberesolvedfromthei18nmessages.ThevalueMessagePrefixwillbesuffixedwithadot('.')andthenthevalueattributeoftheoptiontoresolvethemessage.Ifthemessagecouldnotberesolved,thevalueispresented.
multiple(optional)-Settotruetogenerateamulti-selectlistboxratherthanadropdownlist.
<g:select optionKey="queryBy" optionValue="queryShow" from="${[[queryBy:'newsTitle',queryShow:'新闻标题'],[queryBy:'newsAuthor',queryShow:'新闻作者'],[queryBy:'newsContent',queryShow:'新闻内容']]}" name="queryBy" value="${params.queryBy}"></g:select>
其中的关键是从如何拼装[[queryBy:'newsTitle',queryShow:'新闻标题'],[queryBy:'newsAuthor',queryShow:'新闻作者'],[queryBy:'newsContent',queryShow:'新闻内容']]这种类型的对象,按照groovy的语法,应该是List<Map<String,String>>这种类型的对象。
这个例子是我在做查询时使用select元素让用户按何查询,关键是自定义from属性中的映射然后用optionKey、optionValue指定<option>元素value和显示内容。
生成的HTML代码如下
<select name="queryBy" id="queryBy" > <option value="newsTitle" selected="selected" >新闻标题</option> <option value="newsAuthor" >新闻作者</option> <option value="newsContent" >新闻内容</option> </select>
selected="selected"是根据g:select的value自行判断并生成