translate a HTML select element in Grails

时光怂恿深爱的人放手 提交于 2019-12-10 19:04:29

问题


thought this would be easier.... imagine a <g:select /> like this:

<g:select name="type.id" from="${Type.list()}"   
          value="${domainInstance?.type?.id}"  />

with two domain classes like this (please forgive me if these artificial classes are not error free)

class Domain {
  Type type
}

class Type {
  String name
}

I would now like to translate the entries of the select element. The following code first looked good:

<g:select name="type.id" from="${Type.list()}" 
            valueMessagePrefix="type.name"  
                value="${domainInstance?.type?.id}"  />

with entries in the messagebundle like this:

type.name.type1 = red
type.name.type2 = green

Problem: not only the text was translated, but the option keys, too!

So I tried to add a optionKey='id':

<g:select name="type.id" from="${Type.list()}" 
         valueMessagePrefix="type.name"  
             value="${domainInstance?.type?.id}"  
                optionKey='id' />

This switched the keys to the id - great, but the text switched to the id, too :-(

Any idea how to solve this?


回答1:


thanx to grails beeing open source, I just checked the code: http://grails.org/doc/latest/ref/Tags/select.html#select

It seems that valueMessagePrefix is ignored as soon as you use optionKey or optionValue. But optionValue can take a closure:

<g:select name="type.id" from="${Type.list()}" 
         value="${domainInstance?.type?.id}"  
            optionKey="id" 
            optionValue="${ {name->g.message(code:'type.name'+name) } }"/>

at least, this works.




回答2:


Can't you just add an optionValue?

<g:select name="type.id" from="${Type.list()}" 
         valueMessagePrefix="type.name"  
             value="${domainInstance?.type?.id}"  
                optionKey='id' 
                optionValue='name'/>

Sorry I haven't had a chance to test this exact code, but have done similar things like this with no problems.



来源:https://stackoverflow.com/questions/6948644/translate-a-html-select-element-in-grails

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!