XSLT is a great technology to use to output HTML from Sitecore’s XML. XSLT should be used instead of sublayouts, whenever there is no need for complex logic. However sometimes you need a little chunk of logic to be performed or a simple operation to be executed in your XSLT. XSL extensions are great for this. It allows you to call some C# / VB methods you from your XSLT.
This article will give you an introduction to writing XSL extensions. It will show you, how you configure and call them, but also give some pointer and ideas on when and how to use them.
Setting up:
To create an XSL extension you must follow these steps:
1. Create the C# method you want to call.
2. Declare the extension in the web.config
3. Declare the extension in your XSL file
4. Call the method.
To illustrate this here’s a hello world example:
1: First the c# method:
namespace LearnSitecore.Examples.XSL
{
public class MyXSLExtension
{
public string HelloWorld()
{
return "Hello World!";
}
}
}
2: Now it needs to be declared in the web.config. XSL Extensions are declared in the configuration/Sitecore/ xslExtensions section of the web.config. Here you need to specify the full namespace and class name for the method and a unique namespace to map the declaration in your XSLT. The entry should look like this:
< extension mode = "on" type="LearnSitecore.Examples.XSL.MyXSLExtension, LearnSitecore.Examples" namespace="http://www.learnsitecore.com/examples" singleInstance="true" />
Where the first part of the type is the fully qualified class name and the second part is the dll filename, where the class is placed in. The namespace is used to map the object into the XSL. You can define your own namespace and it hasn’t to be a real URL with an actual page on.
3: To call the method in your XSLT you need to declare the extension as an attribute to the xsl:stylesheet element. As you can see, there are already a few declared. For instance Sitecores own extensions:
< xsl:stylesheet version = "1.0"
xmlns:xsl = "http://www.w3.org/1999/XSL/Transform"
xmlns:sc = "http://www.sitecore.net/sc"
xmlns:dot = "http://www.sitecore.net/dot"
xmlns:ls = "http://www.learnsitecore.com/examples"
exclude-result-prefixes = "dot sc ls">
Here are all the extensions for this XSLT declared. The first thing you need to specify is the namespace declared in the web.config. Further you need to add the prefix you want to use to the exclude-result-prefixes attribute – in this case ls.
Now you can use the extension in your XSLT calling the HelloWorld method:
< xsl:value-of select = "ls:HelloWorld()"/>
Now the “Hello world!” text is outputted.
Congratulations! You have just created your first XSL extension.