How to create a simple Display template in SharePoint & show the managed property value in a content search Webpart


Tarun Kumar Chatterjee
.Net – Technology Specialist
Published On :   03 Jan 2016
Visit Count
Today :  10    Total :   5912



First let’s create a SharePoint list named as “Employee”

clip_image002Create 4 custom site columns: DOB, EmployeeAddress, EmplyeeName & EmployeeTest.

Add the Site columns to the Employee List by using the option “Add from existing site columns”.

Go to SharePoint Central Admin -- > Content Source -- > Start full crawl

Now go to Site & then site settings -- > under Site collection Administration, select Search Schema

If we search the managed property by Employee then we can see that, EmployeeAddress, EmplyeeName & EmployeeTest managed properties are created automatically & the crawled properties are mapped properly with Managed properties

clip_image004

Make sure that Retrieve & Safe properties are enabled for each managed property.

Now create a sandbox solution. Download two default displaytemplates, one for the item and another one for the Control from the site -- > Site settings -- > Display templates -- > Content Webpart & add it to the Sandbox solution

Need to modify the default item template, below is the code of Item template:

 <html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
 <head>
     <title>DisplayTemplate_Test__Item</title>
 
     <!--[if gte mso 9]><xml>
     <mso:CustomDocumentProperties>
     <mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
     <mso:ManagedPropertyMapping msdt:dt="string">'Link URL'{Link URL}:'Path','Title'{Title}:'Title','Line 1'{Line 1}:'EmployeeTestOWSTEXT','Name'{Name}:'EmployeeNameOWSTEXT','DOB'{DOB}:'DOBOWSDATE','Manager'{Manager}:'ManagerOWSUSER','Address'{Address}:'EmployeeAddressOWSMTXT','Line 2'{Line 2}:'' </mso:ManagedPropertyMapping>
     <mso:MasterPageDescription msdt:dt="string">This Item Display Template is designed to help you build a search-driven page. It will show underlying values for the items returned so that you can troubleshoot any issues you may run into. </mso:MasterPageDescription>
     <mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106603</mso:ContentTypeId>
     <mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
     <mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
     </mso:CustomDocumentProperties>
     </xml><![endif]-->
 </head>
 
 <body>
 
     <!--
             Warning: Do not try to add HTML to this section. Only the contents of the first <div>
             inside the <body> tag will be used while executing Display Template code. Any HTML that
             you add to this section will NOT become part of your Display Template.
     -->
     <script>
         $includeCSS(this.url, "~sitecollection/Style Library/CSS/Custom.css");
         $includeLanguageScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Language Files/{Locale}/CustomStrings.js");
         $includeScript(this.url, "~sitecollection/_layouts/15/reputation.js");
         $includeScript(this.url, "https://ajax.aspnetcdn.com/ajax/jquery/jquery-2.1.0.min.js");
     </script>
 
     <!--
         Use the div below to author your Display Template. Here are some things to keep in mind:
         * Surround any JavaScript logic as shown below using a "pound underscore" (#_ ... _#) token
         inside a comment.
 
         * Use the values assigned to your variables using an "underscore pound equals"
         (_#= ... =#_) token.
     -->
 
     <div id="Item_Diagnostic">
         <!--#_
         var encodedId = $htmlEncode(ctx.ClientControl.get_nextUniqueId());
 
         var linkURL = $getItemValue(ctx, "Link URL");
         linkURL.overrideValueRenderer($urlHtmlEncode);
         var line1 = $getItemValue(ctx, "Line 1");
         var Title = $getItemValue(ctx, "Title");
         Title.overrideValueRenderer($contentLineText);
         line1.overrideValueRenderer($contentLineText);
         var containerId = encodedId + "container";
         var currentItemIdx = ctx.CurrentItemIdx + 1;
         var Name = $getItemValue(ctx, "Name");
         var dob = $getItemValue(ctx, "DOB");
         var Address = $getItemValue(ctx, "Address");
         Address = Address.inputValue.substring(Address.inputValue.indexOf("<p>")+3,Address.inputValue.indexOf("</p>"))
         var Manager =  $getItemValue(ctx, "Manager") ;
 
 
         _#-->
         <!--#_
         if(currentItemIdx==1)
         {
             _#-->
         <table id="_#= encodedId =#_" cellpadding="4" cellspacing="4" border="1">
             <thead>
                 <tr>
                     <th>Item Count</th>
                     <th>Title</th>
                     <th>EmployeeName</th>
                     <th>DOB</th>
                     <th>Address</th>
                     <th>Manager</th>
                 </tr>
             </thead>
             <tbody>
                 <!--#_
                              }
                 _#-->
 
                 <tr>
                     <td>
                         <span class="spanchild">
 
                             <!--#_
                             if(!currentItemIdx.isEmpty)
                             {
                             _#-->
                             _#= $htmlEncode(currentItemIdx) =#_
                             <!--#_
                             }
                             _#-->
                         </span>
                     </td>
                     <td>
                         <span class="spanchild">
 
                             <!--#_
                             if(!Title.isEmpty)
                             {
                             _#-->
                             _#= Title =#_
                             <!--#_
                             }
                                 _#-->
                         </span>
                     </td>
                     <td>
                         <span class="spanchild">
 
 
                             <!--#_
                             if(!Name.isEmpty)
                             {
                              _#-->
                             _#= $htmlEncode(Name) =#_
                             <!--#_
                             }
                             _#-->
                         </span>
                     </td>
                     <td>
 
                         <span class="spanchild">
 
                             <!--#_
                             if(!dob.isEmpty)
                             {
                              _#-->
                             _#= ctx.CurrentItem.DOBOWSDATE =#_
                             <!--#_
                             }
                             _#-->
                         </span>
                     </td>
                     <td>
                         <span class="spanchild">
                             _#= $htmlEncode(Address) =#_
                         </span>
                     </td>
                     <td>
                         <span class="spanchild">
                             _#= $htmlEncode(Manager) =#_
                         </span>
                     </td>
                 </tr>
 
 
                 <!--#_
                     if(currentItemIdx == ctx.CurrentGroup.RowCount)
                     {
                    _#-->
             </tbody>
         </table>
         <!--#_
                }
                _#-->
     </div>
 </body>
 </html>
 

Here we are assigning the custom site columns managed property values of

· 'EmployeeAddressOWSMTXT' within the Address variable

· 'ManagerOWSUSER' within Manager variable

· 'DOBOWSDATE' within the DOB variable &

· 'EmployeeNameOWSTEXT' within the Name variable

After assigning all the variables value, start formatting those values by JavaScript on need basis.

Need to modify the default control template, below is the code of control template

 <html xmlns:mso="urn:schemas-microsoft-com:office:office" xmlns:msdt="uuid:C2F41010-65B3-11d1-A29F-00AA00C14882">
 <head>
     <title>DisplayTemplate_Test_Control</title>
 
     <!--[if gte mso 9]><xml>
     <mso:CustomDocumentProperties>
     <mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
     <mso:MasterPageDescription msdt:dt="string">This is the default Control Display Template that will list the items. It does not allow the user to page through items.</mso:MasterPageDescription>
     <mso:ContentTypeId msdt:dt="string">0x0101002039C03B61C64EC4A04F5361F385106601</mso:ContentTypeId>
     <mso:TargetControlType msdt:dt="string">;#Content Web Parts;#</mso:TargetControlType>
     <mso:HtmlDesignAssociated msdt:dt="string">1</mso:HtmlDesignAssociated>
     </mso:CustomDocumentProperties>
     </xml><![endif]-->
 </head>
 
 <body>
 
     <!--
             Warning: Do not try to add HTML to this section. Only the contents of the first <div>
             inside the <body> tag will be used while executing Display Template code. Any HTML that
             you add to this section will NOT become part of your Display Template.
     -->
     <script>
         $includeLanguageScript(this.url, "~sitecollection/_catalogs/masterpage/Display Templates/Language Files/{Locale}/CustomStrings.js");
     </script>
 
     <!--
         Use the div below to author your Display Template. Here are some things to keep in mind:
         * Surround any JavaScript logic as shown below using a "pound underscore" (#_ ... _#) token
         inside a comment.
 
         * Use the values assigned to your variables using an "underscore pound equals"
         (_#= ... =#_) token.
     -->
 
     <div id="Control_List">
 
         <!--#_
         if (!$isNull(ctx.ClientControl) &&
             !$isNull(ctx.ClientControl.shouldRenderControl) &&
             !ctx.ClientControl.shouldRenderControl())
         {
             return "";
         }
         ctx.ListDataJSONGroupsKey = "ResultTables";
         var $noResults = Srch.ContentBySearch.getControlTemplateEncodedNoResultsMessage(ctx.ClientControl);
 
         var noResultsClassName = "ms-srch-result-noResults";
 
         var ListRenderRenderWrapper = function(itemRenderResult, inCtx, tpl)
         {
             var iStr = [];
             iStr.push('<li>');
             iStr.push(itemRenderResult);
             iStr.push('</li>');
             return iStr.join('');
         }
         ctx['ItemRenderWrapper'] = ListRenderRenderWrapper;
         _#-->
         <ul class="cbs-List">
 
             _#= ctx.RenderGroups(ctx) =#_
         </ul>
         <!--#_
         if (ctx.ClientControl.get_shouldShowNoResultMessage())
         {
         _#-->
         <div class="_#= noResultsClassName =#_">_#= $noResults =#_</div>
         <!--#_
         }
         _#-->
 
     </div>
 </body>
 </html>
 
 

Now go to the solution property, assign the Site URL properly & right click on the sandbox solution & deploy.

clip_image006

Go to the site & create a test page.

Edit the page & add a content search webpart within the page.

While adding the webpart select Control template and display template properly.

clip_image008

Now click on the change query

Click on “Switch to Advanced mode”

Within the Query text, add the below query to display the list items within the webpart.

contentclass:sts_listitem ListID:EBED4B4B-3539-4FC9-A34B-F8991DCB6C77

Note: List ID will be differed, need to modify accordingly after list has been created.

Click on Test Query button

It should display the list items on right pane.

clip_image010

Click on apply and save the webpart.

The output will be something like:

clip_image012

Happy coding

Tarun Kumar Chatterjee

Categories