grailsgspgrails-2.0

Access field in multilanguage


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`}

Solution

  • 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.