8

I'm fresh off a couple of haml tutorials, but I can't figure out how to include an html file (directly) into a haml document. For example:

a.haml

.header
    hello
    = render :partial => "b.html"

b.html

world

Expected output:

<div class='header'>
  hello
  world
</div>

I've tried = render "b.html" as well. I get as an error

haml a.haml --trace

test.haml:8:in `block in render': undefined method `render' for #<Object:0x000000018b2508> (NoMethodError)
    from /usr/lib/ruby/vendor_ruby/haml/engine.rb:129:in `eval'
    from /usr/lib/ruby/vendor_ruby/haml/engine.rb:129:in `render'
    from /usr/lib/ruby/vendor_ruby/haml/exec.rb:313:in `process_result'
    from /usr/lib/ruby/vendor_ruby/haml/exec.rb:43:in `parse'
    from /usr/lib/ruby/vendor_ruby/haml/exec.rb:23:in `parse!'
    from /usr/bin/haml:9:in `<main>'

Which sounds like I need to include a library to use "render" or install a library. How do I dump the unformatted text of b.html into the document where I want it?

Hooked
  • 84,485
  • 43
  • 192
  • 261

1 Answers1

15

render is a method from Rails (and some other frameworks), and isn’t available in pure Haml. To include the contents of another file directly you could simply read the file in your Haml:

.header
  hello
  = File.read "b.html"

which gives the input you expect in this case.

This is simple inclusion of the file contents directly in the output though. If you want the other file to be processed in some way you will need to do it yourself, e.g. if you want to render another Haml file you could do something like this:

.header
  Some text
  = Haml::Engine.new(File.read("a_file.haml")).render

If you’re doing this with different template libraries you might want to look at Tilt.

These examples are very simple and you should’t really use them for something like a web app – they’re only really for generating static files. If you’re learning Haml to use in web app development then the helpers from whatever framework you’re using will still be available and you should use those, e.g. render in Rails; haml, erb, markdown etc. in Sinatra.

matt
  • 78,533
  • 8
  • 163
  • 197
  • Thanks that is what I needed, as I'm simply using it as a preprocessor for my own personal static webpage. I didn't realize the distinction between the framework and haml, it's unclear when you search around for it. – Hooked Jan 23 '14 at 22:24
  • @Hooked you should be fine for that use. You might want to have a look at my answer to a similar question: http://stackoverflow.com/a/6131411/214790. – matt Jan 23 '14 at 22:32
  • Thanks for the link! That's the question I will probably be asking in a few days from now. – Hooked Jan 23 '14 at 22:35