Skip to main content

Cloud

URL Encoding in SharePoint XSLT DataViews

When it comes to tweaking the look and feel of SharePoint web parts, one of the best ways is through the use of XSL Transformations. Numerous out-of-the-box web parts can be completely customized through XSLT, including all lists and document libraries.
In my case, I was recently configuring a Content Query Web Part when I ran into a challenge. My template needed to parse fields from a custom list into parameters for a custom page’s query string:

<a href="/Pages/Page.aspx?Title={@Title}&Pragma={@Pragma}">Example</a>

What seemed like a simple task, however, had a major snag: the fields weren’t being scrubbed, and would thus create invalid URLs. For example, if an item was titled "Ben & Jerry’s", the address generated would include "?Title=Ben & Jerry’s", which the server would be unable to process.
The answer, of course, was to URL encode the parameters. It’s something programmers do on a regular basis in a variety of languages, but I had yet to do so natively in SharePoint’s XSLT.
My first approach was to use XSLT 2.0‘s built-in str:encode-uri function. Unfortunately, I soon remembered that WSS and MOSS 3.0 (built on the .NET 2.0 framework) only support XSLT 1.0.
[Side note: After five years in development, XSLT 2.0 was officially promoted to W3C recommendation status in January 2007. Two years later, it’s still not supported in .NET 3.5 and there has been no announcement of official support slated. Don’t expect XSLT in the next version of SharePoint, either. The subject has been hotly contested for years.]
Thankfully, I soon stumbled upon extension functions exposed through the ddwrt namespace. While the set of standard functions available in XSLT 1.0 is somewhat lacking, ddwrt provides dozens of useful functions, such as:

and

Plugging it in is a simple task. First, you need to add the appropriate namespace to your opening xsl:stylesheet tag (this example is for ItemStyle.xsl):

<xsl:stylesheet
  version="1.0"
  exclude-result-prefixes="x d ddwrt cmswrt xsl msxsl"
  xmlns:x="http://www.w3.org/2001/XMLSchema"
  xmlns:d="http://schemas.microsoft.com/sharepoint/dsp"
  xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" 
  xmlns:cmswrt="http://schemas.microsoft.com/WebParts/v3/Publishing/runtime"
  xmlns:xsl="http://www.w3.org/1999/XSL/Transform"
  xmlns:msxsl="urn:schemas-microsoft-com:xslt">

Next, simply use it like any other function:

<a href="/Pages/Page.aspx?Title={ddwrt:UrlEncode(@Title)}&Pragma={ddwrt:UrlEncode(@Pragma)}">Example</a>

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.

PointBridge Blogs

More from this Author

Follow Us