0

I have customized my Announcement web part that adds Read more link on each item of Announcement if the number of characters are more than 250 characters.

It is working the only problem I faced is that text after display lose its format

it just display my text.

how can I keep my text format also?

my codes:

<script>

(function () {

var viewCtx = {};
viewCtx.Templates = {};

viewCtx.Templates.Header = "<table>";
viewCtx.Templates.Item = AnnouncementItem;
viewCtx.Templates.Footer = "</table>";

viewCtx.BaseViewID = 1;
viewCtx.ListTemplateType = 104;

SPClientTemplates.TemplateManager.RegisterTemplateOverrides(viewCtx);

})();

function AnnouncementItem(ctx) {
var headlineLimit = 250;
var headline = $(ctx.CurrentItem.Body).text(); 
if (headline.length > headlineLimit)
{
    headline = headline.substring(0,headlineLimit);
}
return String.format("<tr><td><p><b>{3}</b></p>{1}<a href='{2}/DispForm.aspx?ID={0}'> Read More…</a></td></tr>",
ctx.CurrentItem.ID,headline,ctx.listUrlDir,ctx.CurrentItem.Title);
}

</script>
  • Could you share a screenshot for the same? – mohitcreative Nov 4 '14 at 11:43
1

It occurs since .text() function returns a string containing the combined text of all matched elements:

var headline = $(ctx.CurrentItem.Body).text(); 

The purpose of using .text() function since there is no straightforward ways of truncating html content.


But there are some truncation utilities available, for example jQuery.truncate(html, options). The following example demonstrates how to truncate Body with preserving html tags using this library:

<script type="text/javascript" src="/SiteAssets/jquery.truncate.js"></script>
<script>

(function () {

   var viewCtx = {};
   viewCtx.Templates = {};

   viewCtx.Templates.Header = "<table>";
   viewCtx.Templates.Item = AnnouncementItem;
   viewCtx.Templates.Footer = "</table>";

   viewCtx.BaseViewID = 1;
   viewCtx.ListTemplateType = 104;

    SPClientTemplates.TemplateManager.RegisterTemplateOverrides(viewCtx);

})();

function AnnouncementItem(ctx) {
   var headlineLimit = 512;
   var headline = ctx.CurrentItem.Body; 
   if (headline.length > headlineLimit)
   {
      headline = jQuery(headline).truncate({ length: headlineLimit }).html();
   }
   return String.format("<tr><td><p><b>{3}</b></p>{1}<a href='{2}/DispForm.aspx?ID={0}'> Read More…</a></td></tr>",ctx.CurrentItem.ID,headline,ctx.listUrlDir,ctx.CurrentItem.Title);
}
</script>

Prerequisites:

jquery.truncate.js file have to be uploaded into Site Assets library

  • 1
    Great code thanks for your great help wish you more success – Mehdi Jalal Nov 6 '14 at 9:26

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.