Access field in multilanguage

49 Views Asked by At

I have a simple domain something like this:

class Family {
    String name_en
    String name_fr
} 

In a controller I retrieve all the records in that domain with an executiveQuery like this:

   def family =Family.executeQuery("select new Map(name_en as name_en, name_fr as name_fr) from Family")

I'm simplify the actual code for the sake of clarity. Then I have a GSP page that show this data, but I want to show based on the language. So generally I get the language with this code:

<g:set var="lang" value="${org.springframework.web.servlet.support.RequestContextUtils.getLocale(request).getLanguage()}"/>

but how can I select the name based on the language, here I got the en

 <g:each in="${family}" status="index" var="record">
                       
  ${record?.name_en}

 </g:each>

I thought I could do something like this, but of course it doesn't work:

${record?.name_`lang`}
2

There are 2 best solutions below

0
Joshua Moore On BEST ANSWER

I think it would be easiest to use a dynamically generated property name in this case:

${record?."name_${lang}"}

One of the great things about GString & Groovy.

2
tom6502 On

You will need a bunch of if-then-else.

 <g:each in="${family}" status="index" var="record">
     <g:if test="${lang == 'en'}">
         ${record?.name_en}
     </g:if>
     <g:elseif test="${lang == 'fr'}">
         ${record?.name_fr}
     </g:elseif>
 </g:each>