SQLTerminal.app
now available

XPath.app
now available
Want fresh tech tips in your inbox?

How to Render Partials with an Underscore in Sinatra

       

Sinatra doesn't have a method for rendering partials. It defers to the template language of your choice. For instance, if you're using ERB, it's as simple as


erb :'path/to/partial'

Rails has a nice convention of using an underscore to mark files as partials.


<%= render 'path/to/partial' %> 

Will resolve the path 'path/to/_partial'. But it's a little ugly to look at the underscore in the file path in your templates.

To get this same thing in Sinatra, you can wrap partial rendering in a helper function.


helpers do
  def partial(template, opts={})
    parts = template.split('/')

    last = "_#{parts.pop}"

    erb([parts, last].flatten.join('/').to_sym, {layout: false}.merge(opts))
  end
end

We can pass additional argument to the partial function if we want to use locals, for instance.

Tagged w/ #sinatra #ruby #webapps

Apps I've Built

XPath Expression Editor
Practice and improve your XPath skills with XPath Editor
Click to buy on the App Store
Photo Location Changer
Easily change the location on your photos and videos
Click here for more info about the app
Photo Date Changer
Easily change the dates and times on your photos and videos
Click here for more info about the app
VocabReminder
English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
VocabQuiz
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app