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, :spacertemplate => 'postspacer' %>

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 friendlyid 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 "disqusthread", like so:

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

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


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


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

Unfortunately, :locals doesn't pass to the :spacertemplate - 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="<%= posturl(post) + '#disqusthr...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.