Partial HAML templating in Ruby without Rails

后端 未结 5 720
Happy的楠姐
Happy的楠姐 2020-12-24 08:23

I really don’t need the overhead of Rails for my very small project, so I’m trying to achieve this just using just plain Ruby and HAML.

I want to include another HAM

5条回答
  •  不知归路
    2020-12-24 08:57

    I've done this before, just for a quick-and-dirty template producer. The easiest way is to just render the HAML inside the parent object:

    %p some haml that's interesting
    = Haml::Engine.new('%p this is a test').render
    %p some more template
    

    You'll more than likely want to build some methods to make this easier--a couple of helper methods. Maybe you write one called render_file that takes a filename as an argument. That method might look something like:

    def render_file(filename)
      contents = File.read(filename)
      Haml::Engine.new(contents).render
    end
    

    Then, your template would look more like:

    %p some template
    = render_file('some_filename.haml')
    %p more template
    

    Note, you will probably need to pass self to the original Haml::Engine render so that it knows how to find your render_file method.

提交回复
热议问题