What Is an Attribute Value Template in XSLT?

An Attribute Value Template (AVT) in XSLT is a syntax mechanism that allows dynamic XPath expressions to be evaluated directly within literal result element attributes. Instead of using verbose <xsl:attribute> elements to generate dynamic attribute values, developers enclose XPath expressions inside curly braces ({}) within standard HTML or XML attribute values. This article explains the fundamentals of AVTs, demonstrates how the curly brace syntax functions, outlines where it can and cannot be used, and details the rules for escaping literal braces.

Understanding the Need for AVTs

When transforming XML using XSLT, stylesheets frequently output literal result elements, such as HTML tags. Often, attributes on these elements need values extracted dynamically from the source XML.

Without Attribute Value Templates, injecting dynamic data into an attribute requires the <xsl:attribute> element:

<a>
  <xsl:attribute name="href">
    <xsl:value-of select="url"/>
  </xsl:attribute>
  <xsl:value-of select="title"/>
</a>

While functional, this approach is verbose and clutters template markup. AVTs provide a concise alternative by embedding the evaluation directly in the attribute.

How Curly Brace Syntax Works

The curly brace syntax ({ }) acts as an inline evaluator. When an XSLT processor encounters an attribute value containing curly braces, it evaluates the enclosed XPath expression and replaces the expression (along with the braces) with the string result.

The previous example can be written using an AVT as:

<a href="{url}">
  <xsl:value-of select="title"/>
</a>

You can combine static text, variables, functions, and multiple XPath expressions within a single attribute string:

<img src="/images/{category}/{@id}.jpg" alt="{normalize-space(description)}" class="item-{$theme}"/>

In this case:

Where AVTs Can and Cannot Be Used

AVTs are valid only in specific locations within an XSLT stylesheet:

AVTs cannot be used in:

Escaping Curly Braces

To output a literal curly brace inside an attribute that supports AVTs, double the brace character:

For example, when generating an inline CSS style or JavaScript snippet inside an HTML attribute:

<div style="background-color: {color}; width: {{100px}};">Content</div>

The processor evaluates {color} as an XPath expression while rendering {{100px}} as {100px} in the resulting output.