Re: [xsl] xslt and i18n

Subject: Re: [xsl] xslt and i18n
From: Andrew Welch <andrew.j.welch@xxxxxxxxx>
Date: Mon, 16 Feb 2009 17:06:27 +0000
Regarding localisation support in xslt, I've always thought we could
take advantage of dynamic despatch, import precedence or template
priorities etc

Here's a simple example:

<xsl:stylesheet version="2.0"
    xmlns:xs="http://www.w3.org/2001/XMLSchema";
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform";
    xmlns:f="f"
    exclude-result-prefixes="xs f">

    <xsl:param name="locale" select="'en_GB'"/>

    <xsl:variable name="lang" select="tokenize($locale, '_')[1]"/>
    <xsl:variable name="country" select="tokenize($locale, '_')[2]"/>

    <xsl:function name="f:getLocalisation" as="xs:string">
        <xsl:param name="key" as="xs:string"/>

        <xsl:variable name="lookup">
            <xsl:element name="{$country}">
                <xsl:element name="{$lang}">
                    <xsl:element name="{$key}"/>
                </xsl:element>
            </xsl:element>
        </xsl:variable>

        <xsl:apply-templates select="$lookup/*/*"/>
    </xsl:function>

    <xsl:template match="/">
            <xsl:value-of select="f:getLocalisation('page.title')"/>
    </xsl:template>

    <xsl:template match="page.title">Default Title</xsl:template>
    <xsl:template match="en/page.title">General English page
title</xsl:template>
    <xsl:template match="US/en/page.title">Specific US English page
title</xsl:template>
</xsl:stylesheet>


The key ("page.title" here) and the locale is passed in as a
parameter.  The localised values are stored as templates.  The key and
locale are converted into elements, and then the apply-templates call
is made on that temporary tree... and then the rest is taken care of.

This covers using specific matches, falling back to the general
language when the country specific isn't available (eg falling back to
French when a fr_BE value isn't there) and falling back to a default
when no other exists at all.

The drawback is of course that the translations are hidden within
templates, rather than simple properties files.

Any ideas on how to improve this?


-- 
Andrew Welch
http://andrewjwelch.com
Kernow: http://kernowforsaxon.sf.net/

Current Thread