Display Template Show Limits Characters

Display templates are used to show the queried results in a attractive and useful layout. With the CQWP we used XSLT to format the data as required, but with display templates we need to use JavaScript. One of my most formatted field is the publishing page content field. In this blog post I will explain how you can limit the number of characters shown. In this post I also explain how to remove the HTML markup.

Solution publishing page content
1. Edit the related Item Template.
2. Add the PublishingPageContent to the ManagedPropertyMapping. For a clean example I removed all mappings besides Title and PublishingPageContent.

<mso:ManagedPropertyMapping msdt:dt="string">'Titel':'Title','PublishingPageContent':'PublishingPageContentOWSHTML'</mso:ManagedPropertyMapping>

3. Create a variable for the PublishingPageContent column.

var PublishingPageContentHTML = $getItemValue(ctx, "PublishingPageContent");

4. The PublishingPageContentHTML will contain the page content but with styling. The following code will remove the styling.

var div = document.createElement("div");
div.innerHTML= PublishingPageContentHTML;
var PublishingPageContentL = div.textContent|| div.innerText|| "";

5. In most situations we also want to show a maximum number of characters followed bu three dots. The following code will limit the amount of characters to 175 followed by the required dots. If the content is less then 175 characters long, no dots will be displayed.

var PublishingPageContent = "";
if (PublishingPageContentL.toString().length > 175) {
	PublishingPageContent = PublishingPageContentL.toString().substring(0,175) + "...";
}
else {
	PublishingPageContent = PublishingPageContentL;
}

6. Us the code below to display the PublishingPageContent.

<div>
   _#= $htmlEncode(PublishingPageContent ) =#_
</div>

 

Result

CSWP Result

Share

4 Replies to “Display Template Show Limits Characters”

  1. Very nice blog post. Helped me a lot. But why on earth would you want to block copy / paste from a blog where you publish sample code?
    You either want to share your knowledge or not. At least include a copy function for your code blogs.

Leave a Reply to Remco de Groot Cancel reply

Your email address will not be published. Required fields are marked *