Jump to content

Umbraco/Samples and Articles/XSLT/Extend Xsl

From Wikibooks, open books for an open world

Extend XSL using Javascript, VB or C#

[edit | edit source]

Originally from http://www.umbraco.org/frontpage/documentation/articles/sampleofthemonth.aspx

When developing using xsl, the language sometimes falls short or its difficult and time consuming to accomplish what is easily done in other programming languages.

Answering a question in the umbraco mailing list, revealed that it wasn't common knowledge that you could extend xsl with inline code of your favorite programming language, but it is in fact very easy to do so.

An example using inline server interpreted Javascript.

<?xml version="1.0" encoding="UTF-8"?>
	<xsl:stylesheet 
		version="1.0"    
		xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
   		xmlns:msxml="urn:schemas-microsoft-com:xslt"    
		xmlns:msxsl="urn:schemas-microsoft-com:xslt"    
		xmlns:math="http://exslt.org/math"    
		xmlns:umbraco.library="urn:umbraco.library"    
		exclude-result-prefixes="msxml math umbraco.library"> 
		
		<xsl:output method="html"/> 
			<xsl:param 
				name="currentPage"/> 
				
				<msxsl:script 
					language="JavaScript" 
					implements-prefix="math"> 
						<![CDATA[ 
						function random(){ 
							return Math.random();
						} 
						]]> 
				</msxsl:script> 
				<xsl:template match="/">
					<xsl:variable 
						name="nodeset" 
						select="$currentPage/node"/> 
						
						<xsl:value-of 
							select="$nodeset[floor(math:random() * (last() -1)) + 1]"/> 
				</xsl:template> 
	</xsl:stylesheet> 

This above example shows how to get a random node from a nodeset, using a wrapper to the "Math.random()" function from Javascript, in order to generate a random seed.

The javascript is executed serverside - in fact any defined function is compiled to MSIL (wrapped in a class definition), and thus should have little effect on the general performance - other scenarios could result in performance overheads, but - in the soon to be released Umbraco v. 2.1 - it possible to cache the output of your macroes and therefore it should be possible to maintain high performance and at the same time flexibility in the development.

You can use different programming languages, a complete list and further information can be found at http://msdn.microsoft.com/library/default.asp?url=/library/en-us/cpguide/html/cpconXSLTStylesheetScriptingUsingMsxslscript.asp

Author: Kasper Bumbech Andersen