Overriding the presentation of an XSLT List View Web Part

I’ve recently put up a couple of posts on the XSLT List View Web Part (XLV) following some fairly extensive digging into the possibilities for my current project. My other posts on exporting the XLV or modifying the default ‘no items’ message were (I hope!) useful – but nowhere near as useful as this tip/ technique I’ll share with you now.

SharePoint Designer 2010 is the tool of choice for working with the XLV – but it’s not the only tool! Notepad, or my new favourite Notepad++, can take you almost as far with your customisations. One common request is to modify the presentation of an XLV, for example with some conditional formatting. Here is how you can do that in an environment where SharePoint Designer access is not available.

[Note – again I’m not going to go into the rights and wrongs of SPD in a production environment. I’m just taking it as a known fact that direct access with SharePoint Designer is not an option for some people.]

The key to this technique, which I’m going to call XSL Template Override, is that you can selectively specify fields in your XLV that you’d like to customise the presentation of. This can be done through the browser by simply editing the properties of the web part to link to an XSL file which contains a custom template for you particular field.

This probably makes more sense with an example. So take the scenario of an out of the box tasks list. The default display is fine, but a bit boring!

Tasks List XLV - Not Customised

So let’s customise the display so that the current status of a task is presented as a traffic light image rather than plain text.

Tasks List XLV - Customised

Ok, so not revolutionary 🙂 But if I told you that it takes less than 5 minutes to get this result and that you have complete control of the HTML output for that field value then hopefully you’ll begin to see the possibilities of this technique.

The steps to recreate this then (and see below for a tip on how to generate your XSL):

  • Create an XSL file with contents similar to the below:
    <xsl:stylesheet xmlns:x="http://www.w3.org/2001/XMLSchema" xmlns:d="http://schemas.microsoft.com/sharepoint/dsp" version="1.0" exclude-result-prefixes="xsl msxsl ddwrt" xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime" xmlns:asp="http://schemas.microsoft.com/ASPNET/20" xmlns:__designer="http://schemas.microsoft.com/WebParts/v2/DataView/designer" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:msxsl="urn:schemas-microsoft-com:xslt" xmlns:SharePoint="Microsoft.SharePoint.WebControls" xmlns:ddwrt2="urn:frontpage:internal" xmlns:o="urn:schemas-microsoft-com:office:office"> 
    	<xsl:include href="/_layouts/xsl/main.xsl"/> 
    	<xsl:include href="/_layouts/xsl/internal.xsl"/> 
    	
    	<xsl:template name="FieldRef_body.Status" match="FieldRef[@Name='Status']" mode="body">
    		<xsl:param name="thisNode" select="."/>
    			<xsl:choose>
    				<xsl:when test="$thisNode/@*[name()=current()/@Name] = 'Completed'">
    					<img src="/_layouts/images/IMNON.png" alt="Status: {$thisNode/@Status}"/>
    				</xsl:when>
    				<xsl:when test="$thisNode/@*[name()=current()/@Name] = 'In Progress'">
    					<img src="/_layouts/images/IMNIDLE.png" alt="Status: {$thisNode/@Status}"/>
    				</xsl:when>
    				<xsl:otherwise>
    					<img src="/_layouts/images/IMNBUSY.png" alt="Status: {$thisNode/@Status}"/>
    				</xsl:otherwise>
    			</xsl:choose>
    	</xsl:template>
    </xsl:stylesheet>
    
  • Save this into a library on the site, e.g. site assets or the style library
  • Add an XLV to a page and edit the properties
  • In the miscellaneous section modify the XSL Link property to point to your newly uploaded XSL file
    XLV XSL Link Setting
  • Apply the changes and hopefully you’ll see the changes you’ve specified in your XSL file

How does it work?

So, what’s going on with this? Good question. There are some good articles on MSDN and the SharePoint Team Blog about how the XLV works which are worth a read. But, in terms that I can understand, I think basically that SharePoint has all the incredibly complicated XSL to deal with the display of any of the built-in field types, but it’s loaded by the XLV web part in such a way that it’s possible to specify a custom template which takes higher precedence.

Looking at the XSL file that I’ve used you can see that a couple of default XSL files are imported as the very first step. You can see that I’ve created a template for my field, matching against the internal field name (@Status). Before deciding what HTML you want to generate the other important thing to notice is the mode. Header and Body are the common ones but there are others – and looking at the XSL in SPD in a test environment seems to be the easiest way to find these out.

After I have the template, I usually put a ‘hello world’ string in there and point the XLV to the XSL file to confirm that I have the template correct. Then I’m able to fall back on standard XSL to write out the HTML that I’m after for my custom presentation.

As a tip – if you’re XSL isn’t that hot, or you’re just pushed for time – in a test environment try customising an XLV in SharePoint Designer and then switching to the code view. From there you should be able to see the XSL that has been generated for you. Copy and paste and maybe a tiny bit of pruning will give you your custom XSL file.

Gotchas

I’ve been using this technique now for a few weeks in many places and it’s really helped us make some good progress. However, there are a couple of gotchas that I’ve seen:

  • In the XSL you may want to access field values from the ‘row’ that are not displayed in the view. For example, we use it to create links with reasonably complex query strings, passing through values form the original item. In this scenario, we’ve noticed that to reliably use field values they need to be used somewhere in the underlying query. E.g. they either need to be in the view (which can of course be the column you override) or perhaps used to sort or filter the view.
  • Another gotcha is probably fairly common to people who work with XSL a lot. If your XSL is invalid then you’ll see a pretty horrible message about not being able to display the web part where the contents should be. Using this XSL Template Override technique, whilst this is often simply bad XSL, it can seem to happen when in the processing of editing an XSL file and then refreshing a page that is using the ‘old’ XSL. Navigating away and back to the page removes the error, but it’s one to be aware of – and one that I’ll be monitoring.

Conclusion

I’ve found this technique of overriding the XSL in an XLV hugely useful, and I hope you will too. One massive benefit of this is that it can be done without SPD available but there is also another big win – which is that the one XSL file can be re-used multiple times, cutting down on re-work (something that Dave Pyett has also blogged about).

[Update: 25/05/2010 – I’ve recently seen a bug with this approach that can cause the ECB menu and ribbon not to function correctly. I’ve written this up here]

share and enjoy
  • Print
  • Twitter
  • Digg
  • del.icio.us
  • StumbleUpon
  • Yahoo! Buzz
  • Google Bookmarks
  • Facebook

35 comments to Overriding the presentation of an XSLT List View Web Part

  • […] here to read the rest: Overriding the presentation of an XSLT List View Web Part «Glyn … ← 50000 seats Microsoft SharePoint 2010 on FlexPod for VMware […]

  • pdanan

    Hi Glyn,
    Have you ever edit thumbnails (default) view in Asset Library ? I’m curios Why when I just start editing in designer, by selecting XsltListViewWebpart then clicking ‘Customize XSLT – Customize Entire View’ then Save, Then Error ‘..Correlation ID…’ when I open in the browser ?

    • Hi, sorry that’s something I haven’t tried to do before. I have had issues with the Customize XSLT option previously though – it seemed to me (in my scenario) that whenever SPD came across some XSL that it didn’t like, then for some reason it would crash. In your case, if you have access to the server then you could track down the correlation ID in the ULS logs; I’ve had some success of identifying which template in my XSL file was causing issues using this technique. Sorry I can’t be more help.

  • Great post Glyn! I have used the XSL link property to point to copies of the default xsl files to change the rendering of list views but didn’t realise you could just override individual field templates. Very useful – thanks.

  • Hi Glyn,

    Great post! Something I’ll be trying out here as well as I’m still not yet 100% convinced I should allow my users access to SPD.

    Dave.

  • I tried your nice example on the default view in a Task List, just as you have shown.
    The images shows up and all is good until I realize that the Ribbon does not work.
    When I select the item row by click the checkbox the ribbon does not respond.
    Moreover the dropdown edit menu on the item does not work either.
    When I remove the XSL file link in the webpart, the menu and the ribbon works again.

    Anybody tried to fix this bug?

  • […] the presentation of a SharePoint 2010 XSLT List View Web Part (XLV) using a technique called XSL Template Override. After seeing that this this was an option, and loving the control and flexibility it gave, it […]

  • Dhawal Seth

    Hi Glyn,

    Great post.

    I am having problems with the view part in xslv. I am trying to push a custom view definition in the xslv, but somehow it is generating a view definition of its own and it becomes a manual process after deployment to go and configure the webpart with the correct view.

    • Hi Dhawal, thanks. Good timing of your question – I’m actually writing up a post on that at the minute! Basically I think it’s a bug – and the only way I’ve been able to get around it is by adding the web part using SharePoint Designer (which is not ideal or even an option in many scenarios).

      I’ve been looking at the XmlDefinitionLink property to see if that’s an option but without much luck either.

      G

  • Sergey Slukin

    Hi, Glyn!

    I’we tried to customize xslt, but when I set xsl link of web part in page edit mode, I always get javascript error, telling me that certain object are already loaded.

    What I do:
    1 – create xsl using SDP2010
    2 – copy xsl file to style library or 14/tempalates/layouts/xsl (neither works)
    3 – set xsl link on web part

    I’we tried all the forms of urls, even non existing ones.
    I always get JS error:
    Sys.InvalidOperationException: Type SP.EnumerableArray already registered.
    and a few other messages about other JS types.

    Is there any gotcha?
    Thanks in advance!

    Sergey

    • Hi Sergey. I haven’t seen this exact issue before, however some generic trouble-shooting tips when working with the XLV and custom XSL would be to:
      1) Simplify your XSL right down – e.g. just have it say ‘hello world’ at first – and see if you still get JS errors
      2) Gradually build up your XSL in pieces so that you can identify what forces the error
      3) If you’re feeling brave, open up the ULS logs (with ULS Viewer) and see if you can track down what is happening when the error occurs. Occasionally this has pointed me to the right template in my XSL to find an error

      HTH

  • Shiva

    Excellent…!! It work’s fine for the list has one status column, Can you please share if you have any idea, if SharePoint list has more than one status column how it works..!

    Thank you

    • Hi Shiva – the same principle applies if you have more than one column. Simply find the name of the column that you wish to override and create a new template in the XSL file.

      For example, if you had a new column called ‘ProjectStatus’ you would put this into the Match section of a template and provide the HTML you want to be rendered. Make sure to give your new template a unique name though.

  • Shiva

    Thank you Glyn, I tried to loop through.
    Well nice post.

  • Chinna

    Hi Glyn,

    I have an issue in the updraded SP 2010 publishing site. I have XSLT List View Web Part, with a column as Hyper link. It was working good in 2007. Now in 2010 it is displaying as ‘This is Html’. Can you please suggest me any solution?

    Thanks
    Chinna

  • […] SharePoint Designer. This is a nice solution for a really really useful web part, especially when combined with easily added custom XSL in the XLV. However, I’ve run into a problem with this when the list I’m trying to display has content […]

  • Great post!

    I have some questions though:

    1) When I put the xsl in _layouts I see “file not found” exceptions in the log. is there a workaround?
    2) The example works great on tasks lists and other lists with choice fields but I couldn’t make it work with simple text or calculated fields – is it a bug / feature or simply requires a different xsl because I couldn’t make it work on such cases.

    Thanks!

  • Problem solved: mode=”Text_body” made it work just fine.

  • Mark Wilson

    Have you found a way to include the values of other fields in the template?

    • Hi Mark – I’ve not found a way yet unfortunately. In fact I don’t think it will be possible without specifying those additional fields in the view in some form. You may be able to ‘trick’ it to return the fields by including a dummy filter criteria, such as field1 not equal to lorem but that may not always be appropriate.

      HTH

  • Jóhann Haukur

    Hi Glyn

    I apologize for this tangent question, writing this at home.

    So if I do my custom XSL using those imports and ensuring the mode being correct, will I then be able to customize my list while still getting a proper ‘add new item’ generated at the bottom of the given list?

    I’ve just recently started SP development, and my branding efforts hit a wall when I noticed linking a custom XSL would break the ‘add new item’ functionality, however, I did not do the XSL with fieldrefs, imports and modes like you’re doing there.

    • Hi Jóhann – I think you should be able to do this fine. However, I’ve had issues with the ribbon interaction before, i.e. be able to add a new item from the New Item button in the ribbon, not simply the add new item link.

      Thanks,

      • Sam

        Hello,

        Much like Jóhann I’ve been exploring the best way of modifying SP output of information whilst trying to keep the stock ‘Add New’ and ‘Alert’ links/ribbon items.

        I want to use jQuery UI to, for instance, create an accordion for an announcements list.

        I can now do this with a DVWP (completly bespoke but includes a ‘toolbar’) or CQWP (reusable but no toolbars or ribbon itmes).

        Using XSL linked to a ListViewWebPart sound like the answer but is it possible to modify the entire row of the Web Part?

        Following on is it possible to wrap all the rows in the Web Part in a target-able element ( for instance)

        Thanks
        Sam

        • Hi Sam,

          It is possible to completely override the presentation by using a match=”/” template. Perhaps that gets you closer to being able to integrate JQuery. However, if you want to use the ribbon interaction etc I’d be careful about using custom XSL at all. I’ve had some pretty strange experiences recently with the OOB JavaScript not firing correctly when custom XSL is in place.

          HTH

  • Daniel

    Good post.

    I am seeing that “SharePoint ignores my stylesheet” issue as well. Even in designer with the following added to my xslv web part.

    /Style%20Library/XSL%20Style%20Sheets/BusinessCardView.xsl

    Also I notice that you’ve not parsed through the rows to say

    Is there any reason for this?

    Daniel

    Daniel.

  • Daniel

    Oops

    I missed the markup for the rows in my first comment

  • Graeme

    Thanks!

    I was going round in circles till I found this!

    Much appreciated.

  • Thomas Lamanna

    I know it’s been a while, but I’m having a little trouble. It’s going to sound real dumb, but how do you get this to work with other columns? If I name my column “Status” everything is fine, but when I attempt to modify anything to look at a different column it doesn’t seem to work.

  • Prashant

    Great Post!!

  • GMN

    Hi,
    I am trying to edit the display view of the webpart. I tried this using powershell.

    $webpartmanager=$web.GetLimitedWebPartManager($pageUrl,[System.Web.UI.WebControls.WebParts.PersonalizationSc

    ope]::Shared)
    $webpart = New-Object Microsoft.SharePoint.WebPartPages.XsltListViewWebPart
    $webpart.ListId = $list.ID;
    $webpart.ViewGuid = $list.DefaultView.ID.ToString();
    $webpartmanager.AddWebPart($webpart, “Zone 1″, 0);

    $wptype = $webpart.GetType()
    $viewProperty = $wptype.GetProperty(‘ContextView’,[Reflection.BindingFlags]’NonPublic,Instance’)
    $view = $viewProperty.GetValue($webpart,$null)

    I am getting error at $view = $viewProperty.GetValue($webpart,$null). I am getting valid values in $wptype

    & $viewProperty.

    The error is Exception calling “Getvalue” with “2” argument(s). “Object reference not set to an instance of

    an object”–> system.NullReferenceException: Object reference not set to an instance of an object.
    at Microsoft.sharepoint.WebpartPages.Basexsltlistviewwebpart.Ensureview()
    at Microsoft.sharepoint.WebpartPages.Basexsltlistviewwebpart.get_contextview().

    Can you tell me what is wrong with the code.

    Thanks,

Leave a Reply

You can use these HTML tags

<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>