HTML partials in Sinatra

I was looking for a way to generate an HTML partial (e.g. for web site navigation) within a Sinatra application. Sinatra itself does not have any opinion regarding partials. There are some add-ons out there e.g. sinatra_more aiming for Rails-like helpers content_tag, input_tag etc.

But it seems more natural to me to directly use an HTML/XML library. If I am referencing Nokogiri anyway (Nokogiri is a popular ruby wrapper around the libxml XML library), why not just use that?

builder ||= do |doc|
  doc.ul { 'hello' 'admin', :class => 'current' if current_user.is_admin?
puts builder.doc.inner_html


<li class="current">admin</li>

We do not need any plug-ins and add-ons, it looks easy, does not it? Here is a more elaborated example:

I’ve also done some performance checking:


                  total for 1000 loops, in milliseconds
Nokogiri, singleton builder     0.090000 
Nokogiri, recreate builder      0.270000 
HAML, singleton engine          0.170000 
HAML, recreate engine           1.220000 

So HAML is significantly slower than xmllib, who could imagine that? And caching (evil) can make things faster, and certainly more messy. So I have to think about a helper for helpers that would help you organize your helpers and hide the caching and Nokogiri builder instantiation from you, without hiding too much and introducing leaky abstractions. Stay tuned!


blog comments powered by Disqus