How do you display the first set of characters of a Publishing Page in a display template?

Display templates

I like the usage of Display templates but every now and then there are problems that should be easy to solve that are not. Well, the problem in this article is actually  one of those easily solved problems. Once you know how.

I’ve got a page in my Office 365 SharePoint online environment. I’m using the page content field to collect the article content.

So in my Display Template I’m adding PublishingPageContentOWSHTML

<mso:ManagedPropertyMapping msdt:dt=”string”>’PublishingPageContentOWSHTML’:’PublishingPageContentOWSHTML'</mso:ManagedPropertyMapping>

Then within the JavaScript section of the display template  I’m collecting the summary:

var summary = ctx.CurrentItem.PublishingPageContentOWSHTML;

and I’ve got my html code in the summary variable. If I now get the substring of the summary to get my first 100 characters I might end up with a bit of a mess and most likely nowhere  near 100 characters.

“<p>​Today we have launched the new intranet …. </p><p><span class=\”ms-rteStyle-Normal\”>Lorem ipsum”

Within my display template I’m including some html to display the summary

_#= summary =#_

This will now appear in SharePoint as:

TodayWeLaunched

So now the solution.

first I’m creating a div element

var tag = document.createElement(‘div’);

Then I’m setting the innerHTML of the div that I just created

tag.innerHTML = ctx.CurrentItem.PublishingPageContentOWSHTML;

first set of characters of a Publishing Page

And now the big trick. Set my summary variable to the innerText

var summary = tag.innerText.substring(0,100) + “… “;

So all together this gives me:

var tag = document.createElement(‘div’);
tag.innerHTML = ctx.CurrentItem.PublishingPageContentOWSHTML;
var summary = tag.innerText.substring(0,100) + “… “;

And SharePoint now displays the full first 100 characters:

LaunchedOk
Avatar for Pieter Veenstra

By Pieter Veenstra

Business Applications Microsoft MVP working as the Head of Power Platform at Vantage 365. You can contact me using contact@sharepains.com

3 thoughts on “SharePoint 2013 – Display the first 100 characters of a Publishing Page Content field using Display Templates”
  1. Interesting. I’ve used regex to remove the html tags and then gave a substring in what became. I did this so that if there is a link in the content does not break my layout

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.

Discover more from SharePains by Microsoft MVP Pieter Veenstra

Subscribe now to keep reading and get access to the full archive.

Continue reading