How to add Read More link for your post in the summary page in Orchard Blog

Whenever you create a blog post in Orchard you don't need to show the full content in the home page or in the summary page for posts. By default Orchard will strip all the markups and show only the first 200 characters in the summary.

First, let's find out how Orchard handles this with the help of Designer Tools. If you are using Orchard 1.7 or higher then this module comes with default and don't try to install it because you may run into compatiblity issues. For those with older version you can install them from the Modules section. You need to enable Shape Tracing which will be disabled by default after installation and can be done from Modules as shown below

The shape tracing widget is a very useful component to easily discover information about the rendering code. For more information, please go through this link. When it's enabled an small frame will appear in the bottom of the page with a small icon to the right of the screen. If you click on that it will bring up a window, which is much similar to the developer tools window in chrome. You can discover information about a particular section by clicking on it in the page and then in the tracing window it will display the details as shown below.

The file dealing with the display of the content in the summary page is Common.Body.Summary.cshtml file which is located unded the theme folder, in my case it's Bootstrap. Let's examine the contents of the file by clicking on it and upon analysis you will notice couple of important facts.

  1. If you include a <!--more--> tag in your post, then Orchard will the cut the rest of the content in the summary page.
  2. If it's not there, then it will look for the first paragraph in the post, basically searches for the first <p> ...</p> tag and shows whatever inside that as summary.
  3. If it's unable to find any of these, then it will show the full content of the post in the summary page.

The easiest way for showing the read more link is to use the first option. One thing to note is that whatever changes you made to this file will affect the site globally, ie wherever summary pages are shown the logic used in this file will be used to display it. 

Anyway the code snippet for the same is 

     Orchard.ContentManagement.ContentItem contentItem = Model.ContentPart.ContentItem;
     var bodyHtml = Model.Html.ToString();

     var more = bodyHtml.IndexOf("");
     if (more != -1) {
     	bodyHtml = bodyHtml.Substring(0, more);
     } else {
     	var firstP = bodyHtml.IndexOf("");
     	var firstSlashP = bodyHtml.IndexOf("");
     	if (firstP >= 0 && firstSlashP > firstP) {
     		bodyHtml = bodyHtml.Substring(firstP, firstSlashP 4 - firstP);
     var body = new HtmlString(bodyHtml);

Happy Coding !!!

No Comments

Add a Comment