Search

It’s probably very easy, but I can’t seem to get my head around it. I have a parameter {$language} and I want to retreive the correct information from the following static XML:

<locales>
  <foo>
    <en>A fake object</en>
    <nl>Een nep object</nl>
  </foo>
</locales>

So I have a selector like this:

<xsl:value-of select="/data/locales/foo[$language]" />

But that doesn’t seem to get the job done right since it shows both entries in <foo>. What I want is when $language is ‘en’ it shows the content of locales/foo/en, and when $language is ‘nl’ it shows locales/foo/nl.

Can anyone help me?

I’d say

<xsl:value-of select="/data/locales/foo/*[name() = $language]" />

Thanx, that did the trick!

It made me thinking… isn’t there a way in XSL to make a shortcut for this? for example, create an extra placeholder that would allow you to call

<xsl:value-of select="/data/locales/foo/*[name() = $language]" />

like this:

<locales:foo />

or perhaps:

<xsl:locales name="foo" />

Is there a way to do this in XSL? It would make your XSL stylesheet a bit leaner and cleaner. I know you could do this with xsl:call-template and xsl:with-param, but that would leave you with even more XSL-code!

This would be a good example of using XSL keys. You could create a key of all of elements for the chosen language, and access using the key of the label name itself. For example:

<xsl:key name="labels" match="//locales//*[name()=$language]" use="name(..)"/>

I am setting my $language param manually, but I presume it will be set by some other means in your example:

 <xsl:param name="language" select="'en'"/>

The above key will match all children of locales with an element name matching the language value. To look up into this key you use the name (name()) of the parent of this element (..) which is the label name.

So you get the translated label:

<xsl:value-of select="key('labels', 'foo')"/>

This is actually the first time I’ve properly explored keys, but it seems like the most efficient way of achieving this lookup.

Create an account or sign in to comment.

Symphony • Open Source XSLT CMS

Server Requirements

  • PHP 5.3-5.6 or 7.0-7.3
  • PHP's LibXML module, with the XSLT extension enabled (--with-xsl)
  • MySQL 5.5 or above
  • An Apache or Litespeed webserver
  • Apache's mod_rewrite module or equivalent

Compatible Hosts

Sign in

Login details