Debugging Display Templates


Display Template Series

Last in my series of Display Templates, I’m going to show you how to debug the JavaScript within a Display Template.

There is more than one way to skin a cat, so the saying goes, and this way I’m showing below isn’t the only way.

  1. Once your Display Template is uploaded to your Master Page Gallery, and you have assigned it to your Content Search WebPart, load the page in the browser and then hit F12 to load up the IE developer toolbar. (Obviously you can use Firebug in Firefox if that’s your preferred choice of browser).
  2. Switch the tab to Script. In the drop down list of scripts currently running on your page, find the corresponding .js file to your Display Template.
  3. After selecting it, insert your breakpoint where you wish, and then click the Start debugging link at the menu bar area.
  4. The page will refresh, and when your JavaScript breakpoint is reached, you can then step through the code, and add Watch where needed.

Advertisements

Display Templates and the ManagedPropertyMapping Custom Element.


Display Template Series

Following on from my previous blog Content Search WebPart and Display Templates, I wish to take this further and show how to obtain the properties returned in the search.

In the Header properties of a Display Template, there is a Custom Element called ManagedPropertyMapping. This element Maps fields exposed by search result items into properties available for JavaScript. Used only in item templates.

According to Microsoft the property is comma-delimited list of values that use the following format:

‘property display name'{property name}:’managed property’
example: ‘Known As'{knownas}:’PreferredName’

However while testing to ensure this blog is correct, I’m finding that the property display name and property name is actually the other way round. The examples Microsoft uses always has the property display name and the property name the same. The below picture is setting the ManagedPropertyMapping to the example above.

The below picture is if I swap the property display name and property name around. ( ‘property name'{property display name}:’managed property’ )
example: ‘knownas'{Known As}:’PreferredName’

As you can see from the above pictures, I believe property name and property display name are the opposite way round to what Microsoft have stated.

Property display name
is the property name that shows in the Web Part editing pane when the display template is selected.

Property name is the identifier, in script when obtaining the value of the managed property use would use the property name to call it.

Managed property is a string of one or more managed properties, separated by semicolons. Only in the display template you can map multiple managed properties, when you override using the WebPart edit pane, you can only select one managed property. When multiple properties are selected, they are read in order, and the first value that matches the name of a managed property of the current search item will have its value mapped.

Once a property has been mapped, you can then call it within the JavaScript of the DIV tag section. To obtain a value you would call $getItemValue() passing in current context and the property name. (‘property Name‘{property display name}:’managed property’)

var knownAsValue = $getItemValue(ctx, "knownas");

To use the above variable within the HTML

<div class="cbs-KnownAs ms-nowrap">_#= knownAsValue =#_</div>
 


Content Search WebPart and Display Templates


Display Template Series

In my previous post Brief Introduction into Display Templates I gave an overview of what a Display Template is. In this post I hope to delve a little deeper and show how they are used with Content Search WebParts.

When you add a Content Search WebPart or a Search Result WebPart when you configure the Web Part, you have to select a control and an item display template.

A Control Template is used to show how the results are presented, an HTML structure of the overall layout. The surrounding area that will contain all items returned. For example it could be the heading and footer. The control template is only rendered once within the WebPart.

An Item Template provides the HTML display for an item in the search results. This template will be called for each item in the result set. This allows you to define the layout of the item.

So when the WebPart uses them together it creates a rendered piece of HTML for the webpart.

A display template structure is made up of four main sections. Title, Header properties, Script Block and a DIV block.

Title

Very simply this is the display name that is found in the Display Template sections of the WebPart edit pane.

 <title> My Display Name </title>
 

Header Properties

Following on from the title tag, there is a set of custom elements which provide information about the display template to SharePoint. These elements are surrounded by the following XML markup:

<!--[if gte mso 9]><xml>
<mso:CustomDocumentProperties>
…
</mso:CustomDocumentProperties>
</xml><![endif]-->

An example of an element would be;

<mso:TemplateHidden msdt:dt="string">0</mso:TemplateHidden>
<mso:MasterPageDescription msdt:dt="string">Displays a result tailored for a picture.</mso:MasterPageDescription>

The different properties and descriptions are described here (Taken directly from the Microsoft Website):

Property Description
TemplateHidden Boolean value that indicates whether to hide the display template from the list of available templates in the Web Part. This value can be changed in the display template file properties.
ManagedPropertyMapping Maps fields exposed by search result items into properties available for JavaScript. Used only in item templates.
MasterpageDescription Provides a friendly description of the display template. This is shown to users in the SharePoint editing environment. This value can be changed in the display template file properties.
ContentTypeId The ID of the content type associated with the display template
TargetControlType Indicates the context in which the display template is used. This value can be changed in the display template file properties.
HtmlDesignAssociated Boolean value that indicates whether a display template HTML file has a .js file associated with it.
HtmlDesignConversionSucceeded Indicates whether the conversion process was successful. This value is automatically added to the file by SharePoint, and is used only in custom display templates.
HtmlDesignStatusAndPreview Contains the URL to the HTML file and the text for the Status column (either Conversion successful or Warnings and Errors). This value is automatically added to the file by SharePoint, and is used only in custom display templates.

Script block

The script block is an area where you can add links to include internal, external JavaScript of CSS. You can use SharePoint tokens such as ~sitecollection to obtain URLs. An example shown below:

<script>
   $includeScript(this.url, <a href="http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js">http://ajax.googleapis.com/ajax/libs/jquery/1.9.1/jquery.min.js</a>);
   $includeCSS(this.url, "style library/Slider/css/MySearchWebPartStyle.css");
 </script>

DIV block

The final part is a DIV block with an ID that matches the name of the HTML file. All HTML and code that you want the display template to use must be written within this DIV tag. Please note that this DIV tag is not rendered on the webpage at runtime. As I stated in previous blog, JavaScript code sits within comment blocks that start with <!–#_ and ends with _#–>. HTML sits outside these blocks. You can also uses these blocks control the HTML with conditional statements. Inside HTML attributes that are making script calls or using JavaScript variables need to start with _#= and end with =#_ comment blocks.

Example below taken from the Control_List.html file.

<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>
 

You can use jQuery within your display templates, you must include the jQuery library in your Script Block. Also because jQuery is used to using the # symbol, which is also required in the templates, to reference an ID Selector using jquery it is recommend to use the following code;

var containerQueryId = ‘#’ + ‘_#= containerId =#_’;
$(‘_#= containerQueryId =#_’);

Display Template for Content Search WebPart.

When creating a Display Template it is recommend to copy an existing HTML display template that is similar to the one you wish to create. Once you have copied it and renamed, and reconfigured it, and saved it back to the Master Page Gallery, you will find a corresponding .js file automatically created for you.

By browsing to your publishing site, in the upper right corner of the page, choose Settings, and then choose Design Manager.

In Design Manager, in the left panel area, choose Edit Display Templtes. Your HTML file will now appear with a Status column that will either show “Warnings and Errors” or “Conversion successful”. Please note that Approval Status is set to “Draft” and you need to publish any files added to the Master Page Gallery from within the Master Page Gallery. Once you have converted the template successfully, but going to your web page with eth Content Search Web Part on, when editing you will now see your new template in the corresponding Display Template Control or item.

Brief Introduction into Display Templates


Display Template Series

In SharePoint 2013, for search result Web Part you have the ability to customise your search results. Yes in 2010 you could customise the content query Web Part and search results, but you had to use XSLT to do this. Something I never got round to learning.

In 2013 you have the feature of display templates. Display templates are the combination of html and generated JavaScript which enable the customisation of search results. Used in Search WebParts, Display templates control which managed properties are shown in the search results, and how they appear in the Web Part. You can find the display templates on the site by navigating to;

Site Settings > Master Page Gallery > Display Templates

The Search folder is where the files relevant for the Search Results Web Part are kept. The Content Web Parts folder is where the files relevant for the Content Search Web part are kept.  Now this is the gotcha that made me spend half my morning getting nowhere. If you only see just the .js files within any folder underneath Display Templates, it means you do not have the site collection feature “SharePoint server Publishing Infrastructure” activated. Once this feature is activated, you will see all HTML and corresponding .js files.

Create your own Display Template

I was going to write a step by step guide on how to create your own Display Template, but I believe a simple example by Erik Swenson is a good walkthrough video. http://erikswenson.blogspot.co.uk/2013/01/sharepoint-2013-display-templates.html All I can advise is;

  • Only ever modify the .HTML files. When you upload the html file back into the Display Template folder it will automatically produce the .js file for you.
  • Any JavaScript written within the HTML files needs to be surrounded by <!–#_ javascriptcode _#–> and any reference to JavaScript within HTML attributes needs to be surrounded by _#javascriptcode#_

Reference: http://msdn.microsoft.com/en-us/library/office/jj945138.aspx