Creating custom methods for xslt   

Tags: SharePoint 2010, xslt, Search
Technorati Tags: , ,

This is a small example how can extend the standard xslt function with some custom methods.

In this example we are going to extend the Core result web part and create a method that is going to return the current language the SharePoint site is in.

 

The Code

 

Step 1: Create a new webpart ( not a visual webpart ) and name it ExtendedXSLTSearchWebPart  !


webpart

 

Step 2: Add the following reference “Microsoft.Office.Server.Search” path to the dll => “C:\Program Files\Common Files\Microsoft Shared\Web Server Extensions\14\ISAPI\Microsoft.Office.Server.Search.dll”

Step 3: Add the reference in your code.

using Microsoft.Office.Server.Search.WebControls;

Step 4: Extend the webpart

public class ExtendedXSLTWebPart : CoreResultsWebPart

Step 5: Create a class where you can add method that the xslt can use

public class XSLTMethodManager{
 
}

Step 6: Add the following method to get the current language

public static string GetLang() {
   return System.Threading.Thread.CurrentThread.CurrentUICulture.TwoLetterISOLanguageName.ToLower();
}

Step 7: In your webpart override the following method

protected override void ModifyXsltArgumentList(Microsoft.SharePoint.WebPartPages.ArgumentClassWrapper argList)
{
     argList.AddExtensionObject("ONPRVP:LanguageManager", new XSLTMethodManager());
 
     base.ModifyXsltArgumentList(argList);
}

So that was the coding part :) now we have alter the xslt a little bit.

Step 8: Add the reference in the opening tag.

<xsl:stylesheet version="1.0" 
    xmlns:xsl="http://www.w3.org/1999/XSL/Transform" 
    xmlns:srwrt="http://schemas.microsoft.com/WebParts/v3/searchresults/runtime"
    xmlns:ddwrt="http://schemas.microsoft.com/WebParts/v2/DataView/runtime"
    xmlns:ONPRVP="ONPRVP:LanguageManager">

Step 9: Now we have to call the method and we get the result we needed

<xsl:variable name ="lang" select ="ONPRVP:GetLang()"></xsl:variable>
<p><xsl:value-of select="$lang"/></p>

 

This should also work for CQWP but I need to test it first so I’ll keep you guys updated.

Happy coding! :)

 
Posted by  Gilissen Timmy  on  9/6/2011
0  Comments  |  Trackback Url  | 0  Links to this post | Bookmark this post with:        
 

Links to this post

Comments

Name *:
URL:
Email:
Comments:


CAPTCHA Image Validation