This thread helped me write a really killer partials helper that gives you Rails-like partials functionality. I'm really pleased with it!
#partials_helper.rb
module PartialsHelper
def partial(name, path: '/partials', locals: {})
Slim::Template.new("#{settings.views}#{path}/#{name}.slim").render(self, locals)
end
end
-
#app.rb
require 'slim'
require 'slim/include'
require 'partials_helper'
require 'other_helper_methods'
class App < Sinatra::Base
helpers do
include PartialsHelper
include OtherHelperMethods
end
get '/' do
slim :home
end
end
-
#views/home.slim
== partial :_hello_world, locals: { name: 'Andrew' }
-
#views/partials/_hello_world.slim
h1 Hello, World! Hello #{name}!
I initially had only .render({}, locals)
, which meant that the partials didn't have access to any helper methods contained inside OtherHelperMethods
(but home.slim
did). Passing self
into .render
, as the first argument, fixes that (if you're curious about that, look up the Tilt::Template #render
documentation.
With this PartialsHelper, passing locals is optional, as is specifying a different path to the partial (relative to settings.views
).
Hope you get as much use out of it as I do!