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;

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

 

 

Advertisements