Adding excerpts to Webby

So after revisiting my blog I realized that descriptive tutorial entries with code segments are helpful, but they are…long. The front page of my blog was being dragged way too long by those entries. Thus, I needed to add an “excerpt” feature that allows me to partially display an entry and add a ‘read more…’ link for the full post. Rien Heinrichs has done exactly that with his blog created with Webby, and his github page contains the source. I took a look and turns out it was a lot easier than i thought. Here is how to do it:

First you need to choose which part of the article is the excerpt, i.e. what you want to show on the front page. You can easily do that when you are creating your blog entries. In the .txt file, just add a couple lines of embedded ruby as shown below.

<%# The entry meta data is above %>
<% @page[:excerpt] = capture_erb do %> 
   Put the text here that you want to display as the excerpt 
<% end %> 
<%= @page.excerpt %>    # we have to insert the excerpt back into the page 

The rest of your long entry text goes below

Now you need to go to your front page (usually index.html) that displays the blog posts, and check if there is a page excerpt. If there is, display the excerpt, or else display the whole entry. The only tricky part here is that the excerpt doesn’t exist until the page is rendered, so you want to render the page first, then decide whether to display an excerpt or the entry. See the example code below:

<% posts = @pages.find(
       :all,
       :content_type => 'tumblog',
       :sort_by => :created_at,
       :reverse => true
   )
   paginate(posts, 4) do |p| -%>
   <% render(p) unless p.excerpt -%>
   <% if p.excerpt -%>
     <%= RedCloth.new(p.excerpt).to_html%>
     <a href='<%= p.url %>'>Read more...</a>
   <% else -%>
     <%= render(p) %>
   <% end -%>
<% end -%>

You may notice that RedCloth is used to render the excerpt, this is because i use textile to write my entries, so i want to make sure that the textile in the excerpt gets rendered. Be sure to use whatever markup language engine you choose to render the excerpt.

You can see some examples in my repository for this site. Look at the source of this entry and also check out this partial that i use to display posts.

And that’s it, wasn’t that easy!? No more detailed posts clogging up your blog index.

blog comments powered by Disqus

my pic Isaac Liu is currently a software engineer at Apple Inc. working on the iOS performance team. He received his Ph.D in Electrical Engineering and Computer Science at the University of California, Berkeley . His research focus was in real time systems, parallel architectures and programming models. His thesis can be found here
read more…

office 2 Infinite Loop, Cupertino, CA
email liu (dot) isaac (at) gmail (dot) com
cv html / pdf [ updated: 9/05/11 ]
others facebook linkedin twitter picasa github

Recent Blog Entries

Archive...

Tags