21 July 2011

This week I installed Disqus on my blog. I have set up Disqus such that the majority of the Disqus JavaScript code resides in my _post partial. However, I wanted that nice "View Comments" feature on my index view and only my index view (i.e., not in the "show" view).


Previously, I displayed my posts in the index view in a single line using the handy :collection option in Rails 3:


<%= #render :partial => 'post', :collection => @posts, :spacer_template => 'post_spacer' %>

This poses an issue though, because there is now no simple way that I know of to let Disqus interact with each of my posts using a unique identifier the way it wants to (I use slugs generated from the friendly_id gem as my unique identifier for Disqus). You see, the Disqus JavaScript inserts the "comment count" code with respect to links that contain an anchor called "disqus_thread", like so:

For the following link, Disqus will fetch the comment count by the identifier: article_1_identifier
<a href="http://example.com/article1.html#disqus_thr...d" data-disqus-identifier="article_1_identifier">First article</a>

(Look: http://docs.disqus.com/developers/universal/)


Okay, what about putting the #disqus_thread anchor in the spacer partial, like this?


<%= #render :partial => 'post', :collection => @posts, :spacer_template => 'post_spacer', :locals => {:post => post} %>

Unfortunately, :locals doesn't pass to the :spacer_template - I couldn't figure out if there was another way. The spacer template usually contains static data, not data fetched from the DB, which is what I need. I ended up reverting to an old fashioned loop to display my posts, for greater control:


posts#index.html.erb:
<% @posts.each do |post| %>
<%= render :partial => 'post', :locals => {:post => post } %> <a href="<%= post_url(post) + '#disqus_thr...d'%>">View Comments</a>
<% end %>

What do you think? Any feedback? On the plus side, I can eliminate the spacer partial here - one less file to worry about.

blog comments powered by Disqus Back

Ustreet


Peter Kong is a
software engineer.