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

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>
  • 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! – user2004758 Jan 18 '17 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 – Gautam Sheth Jan 19 '17 at 6:36

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.