English dictionary with notifications so you won't forget what you're studying!
Click here for more info about the app
The app that quizzes and scores you on your vocabulary!
Click here for more info about the app

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))

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

Tagged w/ #sinatra #ruby #webapps