Quick Tip – Attribute Value Templates in XSLT

Previously, I blogged about a quick & easy shorthand method for referencing an XSL variable within an attribute value – this capability is really a subset of a capability called “Attribute Value Templates” in XSL (reference).

What’s great about what I’ll call AVTs for short is that you’re not limited to just referencing existing XSL variables; once an AVT is instantiated – by use of the wrapping {} curly brackets – that attribute can then be any valid XSL expression.

Take for example a common use case of dynamically generating some HTML using XSL and, in doing so, wanting to create HTML attributes using data points from your source XML. In the past, you may have done something like this:

   <xsl:attribute name="id">
      <xsl:value-of select="concat('Task',TaskID)"/>
   <xsl:value-of select="Title"/>

But using an AVT, this same line could be re-written as:

<div id="{concat('Task',TaskID)}">
   <xsl:value-of select="Title"/>

This is just a simple example but, in general, if you can create an expression as part of a “value-of select”, you can do it within an AVT. Support for full expressions within an AVT thus helps ensure you can write stylesheets that are now both smaller and easier to read.

Comments are closed.