CodeGarden 10: The sixth annual Umbraco Developer Conference
June 23-25th 2010 - free ASP.NET MVC pre-conference. Register today!

Using inline XSLT and Umbraco Library to manipulate strings from Umbraco Items

 Sometimes you may insert an Umbraco Page Item that returns a string:

Grocery List: <umbraco:Item field="groceryList" runat="server"></umbraco:Item>

But you may not like the resulting format of the string. For instance, if it is returning the values of a Dropdown, Multiple element, you will get a comma-separated list of returned values like this:

My Grocery List: Kale, Celery, Apples, Carrots

Next you want to format the results so that it lists vertically, with no commas. But you do not want to create an entire separate XSLT file just for this simple string formatting. The alternative is to use inline XSLT and the Umbraco Library. Here's how:

Grocery List: <p/>

<umbraco:Item field="groceryList" runat="server" xslt="umbraco.library:Replace({0},',','<br/>')" xsltDisableEscaping="true"></umbraco:Item>

 

Now, the result will look like this:

My Grocery List:

 

Kale

Celery

Apples

Carrots

 

Here's a few things that I learned along the way:

1. The Microsoft XSLT parser supports XPATH 1.0, and not XPATH 2.0, so, we couldn't use, for instance, the XPATH 2.0 very handy 'Replace' function. No problem, the Umbraco libraries have a lot of support to help us out until Microsoft gets around to doing that. In this case, the Umbraco.library.Replace function does the job.

2. XPATH statements, as well as the Umbraco library for string manipulation, usually need a reference to the string that is being manipulated. As in the above, 'Replace' takes three arguments; first the string with which to start, second the string to be replaced (the comma), and third the string to replace with (the HTML line break <br/>). But for the first element, how do we reference back to the Umbraco:Item that we started with? The answer is to use the placeholder {0} - it is a reference to the returned value of umbraco:Item.

3. If you want to insert any HTML tag elements (such as our line break <br/>), you must set the xsltDisableEscaping="true" attribute. Otherwise, the microsoft XSLT parser will escape the characters with &lt and &gt, and you will see the actual text of the HTML in the browser window.