Navigation

Develop XSLT Templates in Three Steps

A variety of Web-related technologies, including SDL Tridion, have the ability to use XSL Transformations (XSLT) to transform XML into almost any other text-based format; which is handy when converting say, component content stored in XML into HTML or XHTML.*

I love sites like W3Schools that provide detailed tutorials and references on how XSLT works. Other "cookbook" references like this one from XMLPlease.com or the actual XSLT Cookbook from O'Reily give practical and useful examples. An online search for "XSLT identity template" will get you started, but where do we go from there?

I want to add some practical advice on how to work with XSLT in different scenarios, starting with this tip:

<xsl:copy-of select="."/> is GPS for XPath.

When developing and moving around nodes, it helps to see the full source of what you're selecting via XPath. The xsl:copy-of function is the printf() of XSL.

When working with XSLT, I typically iterate towards a final template using three XSL functions. The following assumes you're somewhat familiar with XSLT, have read some of the resources above, but might be stuck on where to start or how to troubleshoot a non-matching XPath.

1) I typically start by reviewing the example source XML file or using the copy-of function.

2) For simple text values, I use xsl:value-of, setting the select attribute to the XPath to the right node or attribute I need. This is useful for structured content where you have a title or headline in plain text and you want to place it somewhere in your output.

3) The final (non-trivial) step is to add xsl:apply-templates as needed to do less selecting and more transforming. The resources above can go into further detail in how to replace nodes, remove namespaces, and best use recursion to do some pretty impressive transformations to the source XML.

If you have the ability to innately understand an XML schema and figure out XPath strings on-the-fly, feel free to skip this copy-of, value-of, apply-templates "method." But if you ever find yourself deeply nested in someone else's XSLT template and can't figure out why something doesn't match, these functions can save some time and frustration.

If the Xpath match doesn't do anything, double check the source with <xsl:copy-of select="."/> within context or replace the period with the Xpath you're troubleshooting. If that doesn't give you anything, go one step higher and remove the last node in your Xpath.

*Tridion uses a variety of templating languages from script-based to XSLT to modular templates using HTML-like Dreamweaver syntax and C# building blocks. XSLT may be a strong and elegant tool, but it's only one of several ways to work with content in Tridion or any other Web-related technology stack.

No comments:

Post a Comment

Feel free to share your thoughts below.

Some HTML allowed including links such as: <a href="link">link text</a>.