Adam Fraser
Adam Fraser

Reputation: 6635

Template functions with HAML in Sinatra

I'd like to be able to create template functions in Sinatra HAML templates that themselves contain haml. Is there any way to do this or something similar? It'd be cool if it could work with markdown too.

foo.haml

def foo(x)
   %h2 something
   %p something about #{x}

%h1 Herp de derp
= foo("mary")
= foo("us")

Cheers!

Upvotes: 2

Views: 956

Answers (2)

theotheo
theotheo

Reputation: 2702

Actually, you can do something like this:

# app.rb    

require 'sinatra'
require 'haml'
helpers do
  def foo(name)
    haml = <<-HAML
#hello_block
   Hello, #{name}
HAML
    engine = Haml::Engine.new(haml)
    engine.render
  end
end

get '/' do
  haml :index
end

# index.haml
= foo 'World'    

Upvotes: 2

Jordan Scales
Jordan Scales

Reputation: 2717

Function is close, what you really need is what's known as a partial. These are predefined templates that you can place inside other views. For instance, you may have a comment partial to display a comment's author, timestamp, content, etc. You can then render this partial for each of the comments on a particular post.

Essentially, you'll end up with the following

# _foo.haml.erb
%h2 somthing
%p= x

# index.haml.erb
%h1 Herp de derp
= render :partial => "foo", :locals => { :x => "mary" }
= render :partial => "foo", :locals => { :x => "us" }

Upvotes: 1

Related Questions