Web developers wiki ASP.NET Sitecore Sharepoint Kentico by Evident Interactive

XSL and Codebehind

Modified: 2008/11/18 10:44 by jim - Categorized as: Sitecore


Recently a module was released in the shared source library. With this module it is possible to create a code-behind class for xslt's, so there is no need for an xsl extension.

You can download the package Xsl codebehindhere

To use codebehind in your XSLT's follow the following steps:

1: Add a XSLT file to your Sitecore project, e.g. /xsl/Document.xslt

2: Add the http://www.sitecore.net/codebehind namespace to the XSLT file. This namespace is fixed and is used in all XSLT files using codebehind: C#:
<xsl:stylesheet version="1.0"
    ...
    xmlns:codebehind="http://www.sitecore.net/codebehind"
    exclude-result-prefixes="... codebehind">
3: Reference the Sitecore.Modules.XslCodebehind assembly in your project.

4: Create a .NET class in your project, e.g. /xsl/document.xslt.cs.

5: Add the XslCodebehind attribute to the class, providing the full path to the XSLT file as a parameter: C#:
[XslCodebehind("/xsl/Document.xslt")]
public class Document
6: Add a public method to the class. The method must be XSLT compatible, i.e. accept and return the valid XSLT types and not return null: C#:
public string HelloWorld()
{
   return "Hello from your codebehind file";
}
7: Call the method from you XSLT using the codebehind namespace: C#:
<xsl:value-of select="codebehind:HelloWorld()"/>
NOTE: If you use the XSLT through the Sitecore rendering engine, i.e. add the XSLT to the layout of a template (or item - yikes!) the codebehind will be attached automatically. If you reference an XSLT file directly in your ASP.NET control/page, you have to replace the standard sc:XslFile control with the scxsl:XslCodebehindFile control:

C#:
<scxsl:XslCodebehindFile Path="/xsl/Document.xslt" runat="server" />

source: Shared Source Blog

 © Evident Interactive BV