Saturday, June 7, 2014

Programmatically upload and use SharePoint 2013 Item Display Templates

This is the third post of a series of blog posts on SharePoint 2013 search display templates.

In previous posts I explained about Display Templates in general and about creating new Item Display Templates. But in some scenarios we can’t upload display templates manually through mapped network drives or design manager. Following are few scenarios where we require a programmatic approach to deploy search Item Display Templates.

Let’s assume that we have thousands of site collections in our environment and we have a search web part in each home page. Can we manually update each site? It is not feasible, isn’t it.

Another scenario is where we have a custom site template where all web parts, libraries, master pages, etc.. are provisioned when we create the site. In that situation, the expectation is to apply custom Display Templates automatically if available.

Following are the steps to deploy a search Item Display Template programmatically

1. Create the custom Item Display Template

In the previous post I explained about creating a custom Display Template. In this scenario we use a test site collection to create the template.

2. Create Visual Studio solution

We will create an empty SharePoint solution and add a module to host the Display Template

image

We need to deploy only the JavaScript file. But to make the solution complete we will include the html version also in the module. By the way, html file is helpful when we need to do changes in future. In that case we will perform following tasks

  • Do the modification in html file
  • Upload that file in to the test site
  • Get the generated JavaScript file and replace current file in the module with that file
  • Deploy the project

3. Update the Feature

Update the scope of the feature to be “Site”

image 

3. Update the element.xml file

  1. <Elements xmlns="http://schemas.microsoft.com/sharepoint/">
  2.   <Module Name="DisplayTemplates" Url="_catalogs/masterpage/Display Templates/Search" RootWebOnly="TRUE">
  3.     <File Path="DisplayTemplates\Item_Contoso.js"
  4.           Url="Item_Contoso.js"
  5.           Type="GhostableInLibrary"
  6.           Level="Published"
  7.           ReplaceContent="TRUE">
  8.       <Property Name="Title" Value="Contoso Item" />
  9.       <Property Name="TargetControlType" Value=";#SearchResults;#Content Web Parts;#" />
  10.       <Property Name="DisplayTemplateLevel" Value="Item" />
  11.       <Property Name="TemplateHidden" Value="FALSE" />
  12.     </File>
  13.   </Module>
  14. </Elements>

4. Deploy the solution

Finally we will deploy the solution to make the template available for search web parts

image

Following is the link to the source code

No comments: