问题
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