21 July 2015

Display Templates: Accordion

In this blogpost I will explain how to create an Accordion in SharePoint using Display Templates. I will use the Accordion in Unify to do this. It is a nice looking, space saving solution and its perfecty responsive for mobile devices without any extra effort. Unify is based on Bootstrap, which is a widely used, responsive platform. I would definitely recommend it.

We will base the Accordion on the Search Results Web Part. It will eventually look like this:



Start

The first step is downloading the Starter Display Templates, which you can find in my other blogpost. Save the files and give them a representative name. In case of our Accordion it could be something like 'AccordionControl' and 'AccordionItem'.

Upload the Display Templates (via the browser) to Display Templates -> Search, inside the Masterpage Gallery (Site Settings -> Web Designer Galleries -> Master pages and page layouts). When you uploaded the files, you will see JS files being generated with the same name. If not, something went wrong.

You could also use the 'New' button in the Display Templates folder to create new Display Templates. You should see the options 'Control Display Template' and 'Item Display Template' in the dropdown menu.

Now is a good time to map the Masterpage Library (if you have not done that already, read here how to do that). You can now use Explorer to open the Display Templates and directly edit them in Notepad++ or any other editor.

Content

We will get the Accordions content out of a Custom List. We don't need much more than what SharePoint already generates for us when creating a Custom List, but we do need one more input field, the one for the content of the Accordion items. In this content we should be able to add elements like images, tables and stuff like that, so what we need is a rich text field. There is no default input field in SharePoint that exactly fits our purpose, so we create our own. We don't create the field inside our Custom List, but instead we create it as a Site Column. Why? 1. Because it will have the Site-scope en therefore will be usable through our entire site instead of just the Custom List and 2. because a Site Column will automatically be mapped to a (new) Managed Property, which is exactly what we need to be able to call the value of the input field inside our Display Template.

  1. Navigate to the Site Columns pagina (Site Settings -> Web Designer Galleries -> Site Columns).
  2. Click Create.
  3. Give your Site Column a representative name (I chose 'Content' because of reusability), select Multiple lines of text, choose a generous amount of lines (25 for instance) at the option Number of lines for editing and check whether the option Enhanced rich text (Rich text with pictures, tables, and hyperlinks) is selected.
  4. Click OK.
  5. Your Site Column should now appear in the Site Columns list, default in 'Custom Columns', unless you filled in something different. Now navigate to the Managed Properties page (https://[JouwDomein].sharepoint.com/_layouts/15/listmanagedproperties.aspx?level=sitecol) and fill in your Site Column name in the searchbar. take a screenshot of what you see now (You will need this later, it is the easiest way). If you have an On Premise environment, now is the time to start a full crawl. If you work with SharePoint Online, you will have to wait for a crawl (usually that will take somewhere between 15 minutes and 24 hours to complete). After the crawl has finished, the Site Column should be mapped to a new Managed Property. SharePoint made up its own names for this Managed Property and personally I think it is a bit difficult to find it. The quickest way is to grab your screenshot, go back to the Managed Properties page, search for your Site Column name again and compare it to your screenshot to see which Managed Property is added. Write down the name of that new Managed Property, you will need it later in your Display Template.


  6. Now, create a Custom List and give it a representative name
  7. Go to the List Settings (Ribbon -> List -> List Settings).
  8. Scroll down to the Columns section and click Add from existing site columns, look for your Site Column and add it.
  9. Create a few list items and fill it up with some content.

Web Part

To be able to see the results of the changes we will make in de the Display Templates, we will first have to create the Web Part itself. As I previously mentioned, we will use the Search Results Web Part.

  1. Navigate to the page where you want to place the Accordion.
  2. >
  3. Add a Web Part to the desired Web Part zone.
  4. Choose the Search Results Web Part and click Add.
  5. The next step is to build a query to load the right data into the Web Part.
  6. Navigate to the Edit Web Part menu (see the arrow on the top right of the web part).
  7. Click the Change Query button.
  8. In the Basics tab (make sure Quick mode is activated, you can verify by the link on the top right of the tab-page Switch to Advanced Mode/Switch to Quick Mode) you see Select a query, choose Items matching a Tag (System).
  9. Next, you see Restrict by app, choose Specify a URL and provide the url to the Pictures library you created earlier.
  10. Restrict by tag should remain to Don't restrict by any tag.
  11. Click OK.
  12. Click Apply in the Web Part menu (do not click OK yet!).
  13. What you see now, probably does not impress you very much yet, but you should be able to see some content of the Pictures library now. Do not close the Web Part edit menu yet, because we are going to set the right Display Templates now.
  14. Click the + next to Display Templates.
  15. First, you will see a dropdown menu Results Control Display Template. In the dropdown menu you should find your own Control Display Template now, which you created earlier. Select it. (Don't see it? Did you publish?)
  16. Next are two radiobuttons. Select the second one which says: Use a single template to display items.
  17. Below this radiobutton there is another dropdown menu. You should find your own Item Display Template here. Select it.
  18. Close the + next to Display Templates.
  19. The Display Templates are now set, but we have to change a few other settings as well. These settings display some settings for users (like sorting and other stuff like that) in the Web Part which we don't want to see in an Accordion. So, we will disable them.
  20. Click the + next to Settings.
  21. Uncheck all checkboxes, accept Show ranked results (if we'd turn that one off as well, there will be no data in the Web Part at all).
  22. The number you see below Number of results per page doesn't matter, jQuery is going to take care of that, so you can leave it as it is.
  23. Close the + next to Settings.
  24. Default, SharePoint creates its own design around the web parts. In case of the Accordion, we want to limit this to just a Title, so we will adjust that.


  25. Click the + next to Appearance.
  26. Fill in a name for your Accordion inside the title input field.
  27. At the bottom you can see the Chrome Type setting, with a dropdown menu. Select Title Only in the dropdown.
  28. Click OK and save the page.

Well, that's all concerning the Web Part itself and its settings. It still does not look like an Accordion at all, so let's quickly start working on the Display Templates.

Display Templates

Like I mentioned in my previous blogpost, Display Templates work in sets, one as a wrapper for the whole thing (Control Display Template) and the second as a wrapper for individual items (Item Display Template). Let's start with the first one.

Control Display Template

The Control Display Template doesn't only hold the markup (HTML) for the Web Part, it also holds the references to all necessary CSS and JavaScript files. The latter is what we start with. You can download the necessary files below (upload them to the desired place in SharePoint):

Open your Control Display Template in Notepad++ (or any other editor) en replace everything in between the <script> tags by the code below:
$includeScript(this.url, "~sitecollection/[Path to file]/jquery.min.js");
$includeCSS(this.url, "~sitecollection/[Path to file]/bootstrap.css");
$includeCSS(this.url, "~sitecollection/[Path to file]/style.css");

The next step is loading and using the Javascript for Bootstrap. You should add the code below in between the <!--#_ and _#--> tags and after the line var siteURL = SP.PageContextInfo.get_siteAbsoluteUrl();. Furthermore we create an array, which will add the number-names to the Accordion items by a for-loop. This is needed to determine which item is 'expanded' and the rest will be 'collapsed'.
AddPostRenderCallback(ctx, function() {
$.getScript(siteURL + "/[path to file]/bootstrap.min.js");

var itemNumbers = ["One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight"];

for (var i = 0; i < ctx["CurrentItems"].length; i++) {
$("a.accordion-toggle").eq(i).attr("href", "#collapse-" + itemNumbers[i]);
$(".panel-collapse").eq(i).attr("id", "collapse-" + itemNumbers[i]);
}
});

Now we've loaded and developed everything we need in order to make the Accordion work. Now we have to build the Accordion itself, the markup (HTML) that is. First, add a class 'Accordion' to the first <div> (it is right above the code with which we just loaded the external files). Next, replace all HTML from the <div> with CSS class 'container' by the code below:
<div class="panel-group acc-v1" id="accordion-1">

</div>

Note: Don not remove the most outer div! It will no longer work if you do.

The final step is a small line of code which tells the Control Display Template where to render the Item Display Template. Add this line of code in between the <ul> tags:
_#= ctx.RenderItems(ctx) =#_

To top it all off you should give the Control Display Template a name, add it inside the <title> tag. That's all for the Control Display Template. Let's now move on to the Item Display Template.

Item Display Template

The first thing to do in the Item Display Template is to tell it which SharePoint columns we want to get. That's what the <mso:ManagedPropertyMapping msdt:dt="string"> tag does. You can see that it already contains some values, but we need to add one more: the custom Content we created earlier. We created the input field as a Site Column, which means it automatically got mapped to a Managed Property. This is where you need that Managed Property. In my case the Managed Property was named 'Content1OWSMTXT'. You should add your Managed Property to to the ManagedPropertyMapping tag like this:
'Content1OWSMTXT':'Content1OWSMTXT' Make sure that each set is separated by a comma.

Vervolgens moeten we het 'Content1OWSMTXT' veld aan een Javascript variabele koppelen. Dat doe je binnen de <!--#_ en _#--> tags, onder de regel var siteURL = SP.PageContextInfo.get_siteAbsoluteUrl();:

Next we have to connect the 'Content1OWSMTXT' column to a JavaScript variable. You can do that by adding the code below in between the <!--#_ and _#--> tags and after the line 'var siteURL = SP.PageContextInfo.get_siteAbsoluteUrl();':
var content = $getItemValue(ctx, "Content1OWSMTXT");

Finally we have to add the HTML that we want to render in every item. Replace all HTML from the <div> with CSS class 'item' with the code below:

<div class="panel panel-default">
<div class="panel-heading">
<h4 class="panel-title">
<a class="accordion-toggle" data-toggle="collapse" data-parent="collapse-One" href="#collapse-One">
_#= $htmlEncode(title) =#_
</a>
</h4>
</div>

<div id="collapse-One" class="panel-collapse collapse">
<div class="panel-body">
_#= STSHtmlDecode(content.value) =#_
</div>
</div>
</div>

Note: Don not remove the most outer div! It will no longer work if you do.

Notice here again all pieces of code starting with '_#='. These sentences use the JavaScript variables to call the SharePoint columns.

That's it! If you refresh the page on which you've placed the Accordion, you should be able to see it in all its glory ☺

To make it easy, you can download the examples of the finished files right here:

13 March 2015

Display Templates: Slider

In this blogpost I will explain how to create a slider in SharePoint using Display Templates. The slider will cover the entire screen width. To do this, I will use the Revolution Slider in Unify. It is a beautiful, responsive slider, which makes it suitable for mobile devices without any extra effort. Unify is based on Bootstrap, which is a widely used, responsive platform. I would definitely recommend it.

We will base the slider on the Search Results Web Part. Because we want the slider to cover the entire width of our screen, we have to create a custom Page Layout for it as well. The slider will eventually look like this:



Start

The first step is downloading the Starter Display Templates, which you can find in my other blogpost. Save the files and give them a representative name. In case of our slider it could be something like 'SliderControl' and 'SliderItem'.

Upload the Display Templates (via the browser) to Display Templates -> Search, inside the Masterpage Gallery (Site Settings -> Web Designer Galleries -> Master pages and page layouts). When you uploaded the files, you will see JS files being generated with the same name. If not, something went wrong.

You could also use the 'New' button in the Display Templates folder to create new Display Templates. You should see the options 'Control Display Template' and 'Item Display Template' in the dropdown menu.

Now is a good time to map the Masterpage Library (if you have not done that already, read here how to do that). You can now use Explorer to open the Display Templates and directly edit them in Notepad++ or any other editor.

Next step is to create a Pictures Library in SharePoint. Give it a name without spaces! This is very important, because SharePoint does not like spaces, so if it finds spaces in the url, it will not work. Upload some images to the library. Keep in mind that the slider will have a fixed height, but a flexible width. The size of the images should be small in height and very very wide in width. Do also fill in the Title and Description fields, we will also use those in the slider.

Page Layout

The slider will be flexible in width, but always the same width as your screen. To achieve that, we have to adjust the markup (HTML) on the page. We are going to create an 80% width page, but the slider will cover full width.

First, create a new Page Layout. You can do that by copying an existing one, but you can also navigate to the Masterpage Library using the browser (~/_catalogs/masterpage/Forms/AllItems.aspx) and select the arrow next to New Document. A list will appear, which contains a Page Layout option.
Another option is to navigate to the Design Manager and create a Page Layout in there. I usually do the latter myself.

Add the code below to the <!--MS:<asp:ContentPLaceHolder id="PlaceHolderAdditionalPageHead" runat="server">--> of the Page Layout (all the way on the bottom, right before the closing tag): <!--MS:<style type="text/css">-->
/* The default contentBOx has margins. We don't want that, because our slider should cover the entire width of the page. So... We remove the margins here. */
#contentBox {
margin: 0;
}

/* The sidenav is now on top of the slider. We would like to push it below the slider, next to the rest of the content. If we don't, the sidenav will push the slider down which is not very pretty. */
#sideNavBox {
position:relative;
top:500px;
}

/* Because of the slider being flexible, it will shrink when your screen resolution gets smaller. We use mediaqueries to adjust the relative distance between the sidenav and the slider when it shrinks. In case of IE, this will only work in version 9 and up. */
@media screen and (max-width: 1024px) {
#sideNavBox {
top:450px;
}
}

@media screen and (max-width: 880px) {
#sideNavBox {
top:450px;
}
}

@media screen and (max-width: 730px) {
#sideNavBox {
top:450px;
}
}

/* It is quite likely that you want to add more content to the page than just the slider. The contentPositioner positions a <div> on a distance of 220px (sidenav width) from the left and 15px from the top. */
.contentPositioner {
margin: 0 auto 0 220px;
padding-top: 15px;
}

/* Below are three Web Part zones, two narrower and a wider one. */
.wpzLeft {
float: left;
width:25%;
margin:0 2% 0 0;
}

.wpzCenter {
float: left;
width: 46%;
}

.wpzRight {
float: left;
width: 25%;
margin: 0 0 0 2%;
}
<!--ME:</style>-->

It is 'best practise' not to use inline CSS code, so usually you should put the styling of Page Layouts inside the your common custom CSS file which you call in the of a custom MasterPage or in the Additional CSS settings. Right now, I put the CSS in like this, because I want to focus on this specific page, without considering the hassle around it. Inside the CSS file I used comments to describe what every sentence does, in case you would be interested ☺

The next step is to add the HTML to the page layout. You can download it here.
Replace all code inside the <!--MS:<asp:ContentPlaceHolder id="PlaceHolderMain" runat="server">--> tag, except the Title snippet. In this code the Web Part zones are present already. All Web Part zones have their own ID. It might cause problems on your SharePoint site. If it does, you should generate your own IDs using the Snippet Tool (Design Manager) or SharePoint Designer.

Last but not least, you have to set the Page Layout to the desired page. You can do that by navigating to the page, click the PAGE tab in the ribbon and click the Page Layout button. You should be able to select your custom Page Layout here, but only if you published it first.

Web Part

To be able to see the results of the changes we will make in de the Display Templates, we will first have to create the Web Part itself. As I previously mentioned, we will use the Search Results Web Part.

  1. Navigate to the page where you want to place the slider.
  2. Add a Web Part to the Slider Zone.
  3. Choose the Search Results Web Part and click Add.
  4. The next step is to build a query to load the right data into the Web Part.
  5. Navigate to the Edit Web Part menu (see the arrow on the top right of the web part).
  6. Click the Change Query button.
  7. In the Basics tab (make sure Quick mode is activated, you can verify by the link on the top right of the tab-page Switch to Advanced Mode/Switch to Quick Mode) you see Select a query, choose Pictures (System).
  8. Next, you see Restrict by app, choose Specify a URL and provide the url to the Pictures library you created earlier.
  9. Restrict by tag should remain to Don't restrict by any tag.
  10. Click OK.
  11. Click Apply in the Web Part menu (do not click OK yet!).
  12. What you see now, probably does not impress you very much yet, but you should be able to see some content of the Pictures library now. Do not close the Web Part edit menu yet, because we are going to set the right Display Templates now.
  13. Click the + next to Display Templates.
  14. First, you will see a dropdown menu Results Control Display Template. In the dropdown menu you should find your own Control Display Template now, which you created earlier. Select it. (Don't see it? Did you publish?)
  15. Next are two radiobuttons. Select the second one which says: Use a single template to display items.
  16. Below this radiobutton there is another dropdown menu. You should find your own Item Display Template here. Select it.
  17. Close the + next to Display Templates.
  18. The Display Templates are set now, but we have to change a few other settings as well. These settings display some settings for users (like sorting and other stuff like that) in the Web Part which we don't want to see in a slider. So, we will disable them.
  19. Click the + next to Settings.
  20. Uncheck all checkboxes, accept Show ranked results (if we'd turn that one off as well, there will be no data in the Web Part at all).
  21. The number you see below Number of results per page doesn't matter, jQuery is going to take care of that, so you can leave it as it is.
  22. Close the + next to Settings.
  23. By default, SharePoint shows a titlebar, which we naturally don't want to see in a slider. So let's turn that off as well.
  24. Click the + next to Appearance.
  25. At the bottom you can see the Chrome Type setting, with (again) a dropdown menu. Select None in the dropdown.
  26. For the elegance, you can set the title to give your slider a name. The name will not be visible, because we just turned the titlebar off.

Well, that's all concerning the Web Part itself and its settings. It still does not look like a slider at all, so let's quickly start working on the Display Templates.

Display Templates

Like I mentioned in my previous blogpost, Display Templates work in sets, one as a wrapper for the whole thing (Control Display Template) and the second as a wrapper for individual items (Item Display Template). Let's start with the first one.

Control Display Template

The Control Display Template doesn't only hold the markup (HTML) for the Web Part, it also holds the references to all necessary CSS and JavaScript files. The latter is what we start with. You can download the necessary files below (upload them to the desired place in SharePoint):

First, we will limit the slider to a maximum height of 400px, everywhere below that amount, it will remain flexible. Open the file 'plugins.css'. On line 76 you will find the selector '.revolution-mch-1:after'. Add the line 'max-height:400px;' to it and save.

Open your Control Display Template in Notepad++ (or any other editor) en replace everything in between the <script> tags by the code below:
$includeScript(this.url, "~sitecollection/[Path to file]/jquery.min.js");
$includeCSS(this.url, "~sitecollection/[Path to file]/style.css");
$includeCSS(this.url, "~sitecollection/[Path to file]/settings.css");

There is also a fallback for older IE browsers, you should add that after the </script> tag:
<!--[if lt IE 9]>
<script>
$includeCSS(this.url, "~sitecollection/[Path to file]/settings-ie8.css");
</script>
<![endif]-->

There is a catch here though. Inside 'style.css' a few other CSS files are called through the @import method. Those CSS files are inside the same folder, so the path is just the filename. Somehow, SharePoint sometimes interprets the paths relative to the site root instead of the folder they are actually in. Therefore you might have to specify the full url in the @import links.
Beside this, I have another problem on one of my SPO environments. When I navigate around the site and return to the slider page (look at it as refreshing the page without a server refresh, F5 instead of CTRL + F5), the additional CSS files, which should be loaded through the @import method, are not loaded at all. If you run into this problem as well, you can solve it by calling the plugins.css the same way as style.css.
Personally I experienced this problam randomly, have no clue why it sometimes occurs... So if you happen to know, please tell me!

The next step is loading and using the Javascript for the slider itself. You should add the code below in between the <!--#_ and _#--> tags and after the line var siteURL = SP.PageContextInfo.get_siteAbsoluteUrl();:
AddPostRenderCallback(ctx, function() {
$.getScript(siteURL + "/[Path to file]/jquery.themepunch.revolution.min.js", function(){
$.getScript(siteURL + "/[Path to file]/jquery.themepunch.tools.min.js", function(){
$.getScript(siteURL + "/[Path to file]/revolution-slider.js", function(){
jQuery(document).ready(function() {
RevolutionSlider.initRSfullWidth();
});
});
});
});
});

To make sure our slider works correctly, we have to load the JavaScript files in a certain order. By default, files are loaded asynchronously inside the Display Templates. If you use jQuery however, jQuery itself must be loaded before any JS files which depend on jQuery, elseways you will get a 'jQuery is undefined' error. Also, by navigating your site without a server refresh, some JS files may not be loaded, which makes the slider break.
In the code above, we nest functions which forces the JS files to load in a specific order.

Now we've loaded and activates everything we need in order to make the slider work. Now we have to build the slider itself, the markup (HTML) that is. First, add a class 'RevolutionSlider' to the first <div> (it is right above the code with which we just loaded the external files). Next, replace all HTML from the <div> with CSS class 'container' by the code below:
<div class="tp-banner-container">
<div class="tp-banner">
<ul>

</ul>
<div class="tp-bannertimer tp-bottom"></div>
</div>
</div>

Note: Don not remove the most outer div! It will no longer work if you do.

The final step is a small line of code which tells the Cotrol Display Template where to render the Item Display Template. Add this line of code in between the <ul> tags:
_#= ctx.RenderItems(ctx) =#_

To top it all off you should give the Control Display Template a name, add it inside the <title> tag. That's all for the Control Display Template. Let's now move on to the Item Display Template.

Item Display Template

The first thing to do in the Item Display Template is to tell it which SharePoint columns we want to get. That's what the <mso:ManagedPropertyMapping msdt:dt="string"> tag does. You can see that it already contains some values, but we need to add one more: The Image. Add the code below to the ManagedPropertyMapping tag:
‘PictureURL’:’ PictureURL’ Make sure that each set is separated by a comma.

Next we have to connect the 'PictureURL' column to a JavaScript variable. You can do that by adding the code below in between the <!--#_ and _#--> tags and after the line 'var siteURL = SP.PageContextInfo.get_siteAbsoluteUrl();':
var pictureURL = $getItemValue(ctx, "PictureURL");

Finally we have to add the HTML that we want to render in every item. Replace all HTML from the <div> with CSS class 'item' with the code below:

<li class="revolution-mch-1" data-transition="fade" data-slotamount="5" data-masterspeed="1000" data-title="_#= $htmlEncode(title) =#_">
<img src="_#= pictureURL =#_" alt="_#= $htmlEncode(title) =#_" data-bgfit="cover" data-bgposition="left top" data-bgrepeat="no-repeat">
<div class="tp-caption revolution-ch1 sft start"
data-x="center"
data-hoffset="0"
data-y="100"
data-speed="1500"
data-start="500"
data-easing="Back.easeInOut"
data-endeasing="Power1.easeIn"
data-endspeed="300">
_#= $htmlEncode(title) =#_
</div>

<div class="tp-caption revolution-ch2 sft" style="z-index: 6"
data-x="center"
data-hoffset="0"
data-y="190"
data-speed="1400"
data-start="2000"
data-easing="Power4.easeOut"
data-endspeed="300"
data-endeasing="Power1.easeIn"
data-captionhidden="off">
_#= $htmlEncode(description) =#_
</div>

<div class="tp-caption sft" style="z-index: 6"
data-x="center"
data-hoffset="0"
data-y="310"
data-speed="1600"
data-start="2800"
data-easing="Power4.easeOut"
data-endspeed="300"
data-endeasing="Power1.easeIn"
data-captionhidden="off">
<a href="_#= linkURL =#_" class="btn-u btn-brd btn-brd-hover btn-u-light">Read More</a>
</div>
</li>

Note: Don not remove the most outer div! It will no longer work if you do.

Notice here again all pieces of code starting with '_#='. These sentences use the JavaScript variables to call the SharePoint columns.

That's it! If you refresh the page on which you've placed the slider, you should be able to see it in all its glory ☺

To make it easy, you can download the examples of the finished files right here:

20 February 2015

Display Templates - Tips & Tricks

In my previous blogpost I already introduced the SharePoint Display Templates. This blogpost is more like a collection of small things that I ran into while working with Display Templates.

Types of Display Templates

There are different types of Display Templates in SharePoint and of every type there is already a number of templates available in SharePoint. Therefore it is advisable to check if there's any Template already present that fits your needs (For me it's never good enough so I always end up creating my own templates ☺). If you even want to make a tiny difference to the standard templates, don’t change the standard template, but instead copy it and create a new custom one.

You can find an overview of types of- and standard Display Templates here.

Managed Properties

Managed Properties are SharePoint columns which can be retrieved by Display Templates. These come in all shapes and sizes, so there are several different ways to display them. More about that later in this blogpost.

In SharePoint there are more properties than just the Managed Properties, they're called Crawled Properties. It's not possible to retrieve the value of these Crawled Properties directly in the Display Templates. You have to map them to a (existing or newly created) Managed Property. You can read here how to do that.

Personally, I used a Site Collection in SharePoint Online, which means I didn't have access to Central Admin. Instead I created the Managed Properties from within the site collection via this url:
https://[JourDomain].sharepoint.com/_layouts/15/listmanagedproperties.aspx?level=sitecol

Retrieve Managed Properties

In the <head> section of the Item Display Template, there's a <mso:ManagedPropertyMapping msdt:dt="string"> tag. That's where you should define the Managed Properties which you want to retrieve. It looks something like this:
<mso:ManagedPropertyMapping msdt:dt="string">'Link URL'{Link URL}:'Path','Line 1 code'{Line 1}:'Title','Line 2 code'{Line 2}:'Description'</mso:ManagedPropertyMapping>

The syntax to define a Managed Property looks like this: 'Property Display Name'{Property Name}:'Managed Property Name'

  1. Property Display Name is, according to Microsoft, the property name that shows in the Web Part editing pane when the display template is selected. I don't really get what they mean here. I don't see it anywhere. If anyone knows more about this, I'd be happy to hear about it!
    As far as I know, this is the value with which you call the Managed Property in the script on the Display Template.
  2. Property Name is an identifier that uses localized string resources to look up the name of the managed property. It is also the value that appears in the Property Mappings section of the Web Part settings menu. When you edit the settings for a Web Part, you can change this value to change what managed property is associated with the field that appears in the Web Part.

    This property is only useful if the Web Part settings menu has the 'Property Mappings' option. If it has not, you can skip this part of the syntax and just use this:
    'Property Display Name':'Managed Property Name'
  3. Managed Property Name is a string of one or more managed properties, separated by semicolons. At run time, the list is evaluated from left to right, and the first value that matches the name of a managed property of the current search item will have its value mapped to this slot. This enables you to write a display template that can work with multiple item types and that can use consistent rendering if compatible properties are present.

After you map a property, you can get its value in script by using the following code inside the <body> tag:
<!--#_
var title = $getItemValue(ctx, "Line 1 code");
_#-->
For this example, I have partially copied the standard SharePoint TwoLine Item Display Template (and modified it a bit), because it makes it very clear where the three different values show up.

You can use variables within the sections of JavaScript as you typically would, to manipulate variables and create HTML strings to be rendered on the page at run time. But, to reference variables declared in the script directly in the HTML, you must use the following format:
_#= variabele =#_ In case of a text value it makes sense to use this syntax:
_#= $htmlEncode(variabele) =#_ The htmlEncode encodes the characters that can crash a script. For example, a quote (') will be encoded to &#39;.

Take a look in the standard Display Templates library that SharePoint has to see what the possibilities are. Furthermore, this website has a lot of valuable information about scripting in Display Templates.

Displaying images

The image and icon Managed Properties actually consist of just text, a url to be precise. To convert it to a visible image, you have to call the Managed Property inside the src of a <img> tag. It would look something like this:
<img src="_#= variabele =#_" alt="" /> There is a catch here though. SharePoint doesn't like urls with spaces in it… Usually spaces are converted into %20, but unfortunatly not in this case. Therefore you have to make sure that the Picture Library in which the images are stored, does NOT contain spaces. Another option is to put some JavaScript together that turns spaces into %20 (don't know how to do that, never tried).

Displaying dates

This is a nice one as well, because you have the freedom to choose the format you prefer. It could look something like this: _#= variabele.format("d MMMM yyyy") =#_ You can also split up the date. I created a colored square myself, in which I displayed the date in two separate pieces. The day and month are displayed below each other instead of inline: <div class="date-formats">
<span>_#= variabele.format("d") =#_</span> <!-- day in integer -->
<small>_#= variabele.format("MMMM") =#_</small> <!-- month in string -->
</div>

There's an overview of all available date formats here.

Displaying file type icons

File type icons are a special case, because it doesn't work the way you would expect, at least not in Search Result Display Templates (no idea why, but it is what it is). The file type icon is the little icon in the first column, for example in Document Libraries, that indicates the type of document. It can be a MS Word icon, or Excel, PDF, etc.

To get it done anyway, we're just going to steal it out of a ContentBySearch Display Template. Here's how to do that:

  1. Add the following code into the tag of the Control Display Template: <script>
    $includeScript(this.url, "/_layouts/15/search.cbs.js");
    </script>
  2. Add the following line of code to the '<!--#' section in the Item Display Template: var iconUrl = Srch.ContentBySearch.getIconSourceFromItem(ctx.CurrentItem);
  3. Call the variabele in an <img> tag like this: <img src="_#= $urlHtmlEncodeString(iconURL) =#_" />

And we're done! I didn't cover any styling here, so it might be that you still have to fix that. I'll soon release a detailed tutorial about creating a 'My Documents' Display Template, in which I also cover the file type icon.

Well, that's it for now, hopefully this was useful to you ☺

Wil je dit in het Nederlands lezen?

SharePoint 2013 - Display Templates

Display Templates are sort of stand-alone files in which Managed Properties (SharePoint columns, like Title, Description, etc) are being retrieved and HTML, CSS en JavaScript can be processed. These files can be rendered in one or multiple pages of your SharePoint site. They’re used in order to control the display of Web Parts. Display Templates consist of two separate HTML files and with each of these files, a JS file is automatically being generated and attached. You will not be doing anything with these JS files, SharePoint does that automatically.

The first HTML file is the Control Display Template and the second is the Item Display Template. The Control Display Template determines the overall structure of how the results are presented (like lists, lists with paging, slide shows, etc). For example, a <ul> in which you will later render <li>'s.

The Item Display Template determines how each result in the set is displayed (like list items, images, text, ect). That would be the <li> (and its content) which we named in the previous example. Just one <li>? Yes, it’s a template, so a script will loop through and reuses the same <li> over again. The Web Part settings decide how many items are displayed, the templates have nothing to do with that.

The reason there are two separate (Control and Item) files instead of a single one, is the fact that Control- and Item Display Templates can be randomly combined. So they are not necessarily permanent sets. It may well be that you create multiple Item Display Templates for the same Control Display Template, because the Item Templates do use the same markup and styling, but, for example, retrieve the values of different SharePoint columns (Managed Properties).

Nice story, but how do I do this?
Let's start at the beginning. Because I used SharePoint Online myself (where you don't want to deploy from Visual Studio), this blog post will be based on it as well. Therefore we will use the SharePoint Design Manager and Notepad++.

Personally, I like the 'Search Results' method best. It is just one Web Part (the Search Results Web Part), with which you can literally and metaphorically go anywhere you want. You just use a different Search Results Web Part for every Web Part you want on the page, give it its own query and let the Display Templates decide how and what is displayed. Thus, the same Web Part can look completely different and display other data in every instance.
I have to admit that I didn’t figure out every kind of Display Template there is, so I don’t know if in some scenarios there are better alternatives. What I do know is that Search Results work just fine for what I needed to do with it.

Start

You can find the Search Results Display Templates here:
https://[YourDomain].sharepoint.com/_catalogs/masterpage/Display%20Templates/Search/

If you have a child SiteCollection which you want to use, the path would be something like this:
https://[YouDomain].sharepoint.com/sites/[YourSiteCollection]/_catalogs/masterpage/Display%20Templates/Search/

Map Network Drive

The easiest way of working is to map a network drive for the Master Page Gallery of you SharePoint site, so you can access the files via Explorer on your computer. Read this to find out how to do that.
Note that: You have to use IE, you have to check the 'Keep me signed in' option, You have to add your SharePoint domain/site to your trusted sites and you have to open a random library using the 'Open with Explorer' option in the ribbon (only possible in IE). After these steps you should be able to map the MP Gallery. As long as you are logged into the site (via the browser that is), you can use Explorer to access the files in the MP Gallery. If you log out, access will be denied in Explorer as well. In the MP Gallery you can navigate to Display Templates -> Search for the right location.

Starter Display Templates

Below I've put links to some starter templates you can use as a base. The Control Display Template contains a heading and a container for the items, the Item Display Template shows a Title and a Description.


Indeed, the JS files are missing. This is because SharePoint creates those itself, as soon as you upload the files above to the Display Template Gallery. You have to use the SharePoint user interface (the browser) to upload the files though. Unfortunatly, via the mapped network drive the JS files will not be generated at all.

Where to go from here?

It would've become a very very long piece of text if I was going to write down detailed howto’s in this blogpost, so I've created a few separate blogposts to explain a few options:

Finally, I wrote a blogpost with some tips & tricks. Obviously I ran into some issues when I started working with the Display Templates myself. To save you the grief, I wrote the solutions to these issues into this blogpost and also some best practices to prevent problems.

What is also very interesting, is this web page. You can read everything about how and why and the Display Template structure.

Wil je dit in het Nederlands lezen?