Difficulty: ★☆☆ (easy)
Keywords: l10n, translation, language files, local.l10n.xml, context, gentext, http://docbook.sourceforge.net/xmlns/l10n/1.0

Problem

You need a general solution to add localized text without hard-coding it into your stylesheet. Depending on the language, it should display the correct, translated text.

Solution

Use language files to add your text. Language files are the DocBook way to support several languages, all located under the common directory. Each file is in XML format and contains all your translated text as a key/value pair. For more complex settings and to group things, there are contexts. The key is never translated, it is a constant and is only needed to find and retrieve the translated text.

To use a language file, proceed as follows:

Procedure 2.1. Adding Your Own Localized Text
  1. Create a customization layer first as shown in Section 2.3, “Writing Customization Layers”.

  2. Add the parameter local.l10n.xml in your customization layer and point it to your language file (in this case, it is named myl10n.xml, but you can use any name you like):

    <xsl:param name="local.l10n.xml" select="document('myl10n.xml')"/>
  3. Open the myl10n.xml file and insert the following XML code as an example:

    <l:i18n xmlns:l="http://docbook.sourceforge.net/xmlns/l10n/1.0">
      <l:l10n language="en" english-language-name="English">
        <l:gentext key="Authors" text="Authors"/>
        <l:gentext key="lastbuilt" text="Last built: "/>
      </l:l10n>
      <l:l10n language="de" english-language-name="German">
        <l:gentext key="Authors" text="Autoren"/>
        <l:gentext key="lastbuilt" text="Zuletzt gebaut: "/>
      </l:l10n>
    </l:i18n>

    The above code shows two languages, English and German (marked in the language attribute). Furthermore, it contains two text entries for each language (“Authors” and “lastbuilt”).

  4. Call gentext in your template to retrieve the translated text:

    <xsl:call-template name="gentext">
      <xsl:with-param name="key" select="'Authors'"/>
    </xsl:call-template>

Discussion

The “gentext” method to insert language specific text is quite powerful, but not almighty. It helps you to keep translatable text in one place and avoids hard-coded locations in your stylesheets. If you need the translated text not for the default language (usually marked in the root element), but for a different language, use the xsl:with-param as shown:

<xsl:call-template name="gentext">
  <xsl:with-param name="key" select="'Authors'"/>
  <xsl:with-param name="lang">de</xsl:with-param>
</xsl:call-template>

See Also

http://www.sagehill.net/docbookxsl/Localizations.html


Project@GitHubIssue#7