How to render a partial in sinatra view (haml in h

2019-03-09 03:20发布

I have a simple sinatra app that uses haml and sass for the views. One of the views (located in the views folder) is a partial for my navigation menu. I am trying to render it from index.haml but I get the following error: wrong number of arguments (1 for 2)

I am trying to render it with the following lines in index.haml

.navigation
  = render :partial => "nav"

4条回答
Juvenile、少年°
2楼-- · 2019-03-09 03:25

You can just use Sinatra's haml function:

= haml :nav
查看更多
不美不萌又怎样
3楼-- · 2019-03-09 03:28

EDIT: !!! OUTDATED !!! Read Jason's answer below!

What are you trying works in rails! Sinatra has no partial method. An implementation of partial on Sinatra looks like this (source gist) from github:

module Haml
  module Helpers
    def partial(template, *args)
      template_array = template.to_s.split('/')
      template = template_array[0..-2].join('/') + "/_#{template_array[-1]}"
      options = args.last.is_a?(Hash) ? args.pop : {}
      options.merge!(:layout => false)
      if collection = options.delete(:collection) then
        collection.inject([]) do |buffer, member|
          buffer << haml(:"#{template}", options.merge(:layout =>
          false, :locals => {template_array[-1].to_sym => member}))
        end.join("\n")
      else
        haml(:"#{template}", options)
      end
    end
  end
end

Including this method, you may call partial in your .haml files, like
= partial("partial_name")

If you want to render a view in an other view syntax is
= render(:haml,:'rel_path_to_view',:locals => {:optional => option})

Notice the syntax differences between rails and sinatra regarding render method!

查看更多
姐就是有狂的资本
4楼-- · 2019-03-09 03:43

Here's how I do it (more simply than @kfl62's answer, more feature-rich than @jm3's answer):

module Partials
  def partial( page, variables={} )
    haml page.to_sym, {layout:false}, variables
  end
end
helpers Partials

Use it in your Haml file like:

%ul#comments
  - @comments.each do |comment|
    %li= partial :comment, comment:comment
查看更多
5楼-- · 2019-03-09 03:45

Or you could just do this:

helpers do
  def partial(page, options={})
    haml page.to_sym, options.merge!(:layout => false)
  end
end

And include your partial with:

= partial( "something-rad" )
查看更多
登录 后发表回答