1

In sinatra's app,

require 'rubygems'
require 'sinatra'
require 'haml'

get '/new' do
  haml :new
end

get '/edit' do
  haml :edit
end

__END__

@@ layout
%html
  %head
    %title
  %body
  = yield

@@ _form
# partial form

@@ new
%h1 Add a new item
# require partial _form

@@ edit
%h1 Edit an existing item
# require partial _form

How to require the partial @@ _form template in @@ new and @@ edit?

Thank you.

abernier
  • 27,030
  • 20
  • 83
  • 114

3 Answers3

3

Have you looked at this yet: http://www.sinatrarb.com/faq.html#partials?

I created app_helpers.rb and required it in my main app file. app_helpers contains this method:

  def partial(template, *args)
    options = args.last.is_a?(Hash) ? args.pop : { }
    options.merge!(:layout => false)
    if collection = options.delete(:collection) then
        haml_concat(collection.inject([]) do |buffer, member|
          buffer << haml(template, options.merge(
                                  :layout => false,
                                  :locals => {template.to_sym => member}
                                )
                     )
      end.join("\n"))
    else
      haml_concat(haml(template, options))
    end

end

In my views, I use:

- partial :file
Brian Deterling
  • 13,556
  • 4
  • 55
  • 59
1

I would recommend Sinatra-Partial plugin: https://github.com/yb66/Sinatra-Partial

In your code,you just need :install gem 'gem install sinatra-partial'

require partial in your code: 'require 'sinatra/partial'

change your code as follow:

@@ new
%h1 Add a new item
= partial '_form'

@@ edit
%h1 Edit an existing item
= partial '_form'

if you want add some parameters into the _form partial, you can use locals to pass it:

= partial '_form', locals: { param: @param }
xianlinbox
  • 969
  • 10
  • 10
1

If you are using sinatra, why not use it's built-in haml method like so:

= haml :partial_form, layout: false

In rails:

= render 'partial_form'
bbop
  • 91
  • 1
  • 5