The Linux Page

Setting tag attributes in a dynamic way in XSLT with XQuery

I wanted to dynamically manage the attributes of the HTML tag. As I'm working on the Snap! C++ system, I thought that should be done with the standard XSLT feature: <xsl:attribute-set name="...">. Unfortunately the the XQuery implementation does not currently support such, at all.

There is a way, though, to still make it work with a central template definition which can be used to decide what should be and what should not be added to the HTML tag.  Especially, in this way we can make use of one template that is a system defined template. This being said, if you use additional plugins we'll have to support an automated way to support additional attributes specific to other plugins.

So, the result is something as follow:

  <xsl:call-template name="html-attributes"/>

As we can see the HTML tag can be followed by a call to a template which gathers whatever attribute that we want to add to said HTML tag. The template can look as follow:

<xsl:template name="snap:html-attributes">
  <xsl:attribute name="lang"><xsl:value-of select="$lang"/></xsl:attribute>
  <xsl:attribute name="xml:lang"><xsl:value-of select="$lang"/></xsl:attribute>
  <xsl:if test="$use_og = 'yes'">
    <xsl:attribute name="prefix">og:</xsl:attribute>

The template shows that the og: prefix is added only if the $user_og variable was set to yes.