Reputation: 11689
I'm working on a static website (so no real server support) and I would like to include a small slim snippet in another, possibly passing a variable to it.
Is this possible? In rails is quite easy, though the render
method, but I have no idea how to do it on slim (obviously load
method doesn't work for slim).
Upvotes: 5
Views: 7930
Reputation: 2343
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!
Upvotes: 0
Reputation: 496
Slim contains Include
plugin that allows to include other files directly in template files at compile time:
require 'slim/include'
include partial_name
Documentations is available here: https://github.com/slim-template/slim/blob/master/doc/include.md
If you need to include the files at runtime
Slim::Template.new("#{ name }.slim").render
does the job (https://github.com/slim-template/slim#include-helper).
Upvotes: 7
Reputation: 1717
I would strongly reocommend checking out Middleman if you want to build a static website using Slim. Middleman borrows common helper functions like render
and partial
from Padrino, a web framework sort of like Rails but built using the more lightweight Sinatra (all of these are great software).
The poins is that you can configure Middleman to use slim and then nest partials (or layouts as well) arbitrarily. If you run into snags, check this stack overflow thread. It's pretty simple though!
The Middleman docs explain how to use partials here, and you can see how a real-world example looks in my gist for embedding an HTML5 video player.
Upvotes: 2
Reputation: 11689
Looks like it can be done in this way:
Slim::Template.new('template.slim', optional_option_hash).render(scope)
Found in slim readme: https://github.com/slim-template/slim
Upvotes: 1