0

I'm trying to truncate text on an Announcements webpart. I utilized this post, and everything works except the Body variable isn't displayed at all. Here is my code:

<script>(function () { var itemCtx = {}; itemCtx.Templates = {}; itemCtx.Templates.Header = "<div class='announcementsContainer'><ul class='newsHeadlines'>" itemCtx.Templates.Item = announcementsBeautified; itemCtx.Templates.Footer = "</ul></div>"; itemCtx.BaseViewID = 1; itemCtx.ListTemplateType = 104; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx); })(); function announcementsBeautified(ctx){ var headliner = ctx.CurrentItem.Title; var msg = $('ctx.CurrentItem.Body').text(); var author = ctx.CurrentItem.Author[0].title; var date = ctx.CurrentItem.Date; var msgLimit = 275; var html = "<li><div class='announcementsBody'><h3>" + headliner + "</h3> <div class='announcementsDate'><font class='author'>" + date + "</font></div> <br/>posted by <font class='author'>" + author + "</font><br/>" + msg + "<br/>Read More" + "</div></li>"; if (msg.length > msgLimit){ msg = msg.substring(0,msgLimit); } return html }</script> 

1 Answer 1

1

Try below code:

<script>(function () { var itemCtx = {}; itemCtx.Templates = {}; itemCtx.Templates.Header = "<div class='announcementsContainer'><ul class='newsHeadlines'>" itemCtx.Templates.Item = announcementsBeautified; itemCtx.Templates.Footer = "</ul></div>"; itemCtx.BaseViewID = 1; itemCtx.ListTemplateType = 104; SPClientTemplates.TemplateManager.RegisterTemplateOverrides(itemCtx); })(); function announcementsBeautified(ctx){ var headliner = ctx.CurrentItem.Title; var body = ctx.CurrentItem.Body; var msg = body.replace(/<(?:.|\n)*?>/gm, ''); var author = ctx.CurrentItem.Author[0].title; var date = ctx.CurrentItem.Date; var msgLimit = 275; var html = "<li><div class='announcementsBody'><h3>" + headliner + "</h3> <div class='announcementsDate'><font class='author'>" + date + "</font></div> <br/>posted by <font class='author'>" + author + "</font><br/>" + msg + "<br/>Read More" + "</div></li>"; if (msg.length > msgLimit){ msg = msg.substring(0,msgLimit); } return html }</script> 
2
  • that worked perfectly. would you mind shedding light on what replace() [and those symbols] did? and maybe [if you have time], let me know why it wasn't working before? thanks so much! Commented Jan 18, 2017 at 22:34
  • 1
    replace(/<(?:.|\n)*?>/gm, ''); its a regular expression which strips out the html tags and gives you the text inside the html. Since the Body field is Rich text, we use this Regex to remove tags and get the content Commented Jan 19, 2017 at 6:36

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.