You need the language of the current element or of your DocBook document.
Use the l10n.language
template from
common/l10n.xsl
. It extracts the language attribute
from the current context node or its ancestors:
<xsl:variable name="language"> <xsl:call-template name="l10n.language"/> </xsl:variable>
It returns a “normalized” string which is RFC1766 compliant.
If you need to change the current node, use the
target
parameter. For example, the
following code extracts the language from the root element:
<xsl:variable name="lang"> <xsl:call-template name="l10n.language"> <xsl:with-param name="target" select="/*"/> </xsl:call-template> </xsl:variable>
Language information is stored in DocBook either in the lang
(4.x) or xml:lang
(>5.x) attributes. These attributes can be set on every
DocBook element.
For example, if you have a chapter inside a book and want to extract the contents of the language attribute from this chapter, the following XPath expression gives you this information:
/book/chapter/@lang DocBook 4.x /db:book/db:chapter/@xml:lang DocBook 5.x
Although the XPath expressions are simple, they have some drawbacks:
If no language attribute is set, no content can be retrieved. The used language is undefined.
There is no default language when a language is not set.
Language information can be written inconsistently, for
example, en
or EN
.
The above expressions do not take into account the current
context node. For example, the language in a foreignphrase
element is usually different from that of a chapter or other parts of the
document.
There are no checks for RFC compliance.
All the previous problems are considered by the
l10n.language
template. It searches for the
nearest ancestor that contains a language attribute and returns
its content. For example, consider the following structure:
book xml:lang="en" chapter section para foreignphrase xml:lang="de"
If your current context is on the foreignphrase
element, l10n.language
will return
de
as language. However, if your context is
on the para
element, you will get
en
. The para
, section
,
and chapter
elements are children of book
and therefore in the scope of the language attribute which gives
you en
.
In the case no language is given, the template returns a
default language from the
l10n.gentext.default.language
parameter (usually
English).
Sometimes, returning only the language is not enough. The
following table gives you some additional functions from common/l10n.xsl
which can be useful for your code (Question marks(?) denote an
optional parameter):
Template | Description |
---|---|
attrnode = | Useful for HTML. Returns an attribute node lang with the extracted language
from the current node or one of its ancestors |
attrnode = | Useful for XHTML. Returns an attribute node xml:lang with the extracted language
from the current node or one of its ancestors |
string = | Returns the English language name |
Project@GitHub | Issue#7 |