Blog
DIY tips: Multilingual Views
2007-11-09 18:17:08 by Martynas Jusevičius
Using XML as data serialization and XSLT as a templating engine (which DIY Framework does by default), it is pretty trivial to localize your Views for multiple languages.
Simply create an XML file (either one for each specific View or a general one for all the Views) and place it where your XSLT stylesheets can access it. It will contain localized phrases. Each phrase will have a unique identifier and a string value in each of the languages you use. XML has a special reserved attribute xml:lang for identifying the language of the content using language tags. For example:
<phrases> <phrase id="insulation"> <text xml:lang="lt">Izoliacija</text> <text xml:lang="en">Insulation</text> </phrase> <phrase id="mufflers"> <text xml:lang="lt">Slopintuvai</text> <text xml:lang="en">Mufflers</text> </phrase> </phrases>
Then you can access these phrases in your XSLT stylesheet using the filename, phrase ID and a special XPath lang() function:
<xsl:value-of select="document('../phrases.xml')/phrases/phrase[@id = 'insulation']/text[lang($lang)]"/>Here $lang is the code of the language we want to display our View in. It was defined as a parameter of the stylesheet. In that way we select the localized version of the phrase.
How to retrieve the language code (which will be passed as the value of $lang) is a matter of application design. Probably the simplest solution is to specify a request parameter containing a language code on the Resources you want to localize, e. g. Products/?lang=en. You can also implement an automatic language selection using HTTP content negotiation with the Accept-Language header.
