I'm trying to test the formatting of some HAML templates outside of Rails. The idea is to pass in some instance variables on the command line or via an included Ruby file, rendering the template to standard output. I tried this several different ways without success, as outlined below.
For example, given the following two files:
HAML template: "test.haml"
!!!
%h1 Testing HAML CLI
%p= @bar
%p= @baz
Ruby file: "test.rb"
@foo = 'abc'
@bar = '123'
I would expect an invocation like haml -r ./test test.haml
to return an interpolated HTML file on standard output, but it doesn't. Instead, I get just the HTML:
<!DOCTYPE html>
<h1>Testing HAML CLI</h1>
<p></p>
<p></p>
Since this didn't work, I also tried to do this programmatically. For example:
#!/usr/bin/env ruby
require 'haml'
@foo = 'abc'
@bar = '123'
engine = Haml::Engine.new(File.read 'test.haml')
puts engine.render
with exactly the same results, e.g. just the HTML with no variable interpolation.
Clearly, something else is needed to get HAML to render the template with its associated variables. I would prefer to do this from the command line, either by passing arguments or including a file. How should I be invoking HAML from the command line to make it happen?
If that's not possible for whatever reason, how should I invoke HAML programmatically to perform the interpolation without depending on Rails?
You can supply a scope object and a local variables hash to the render
method. In your example case, you would call:
engine = Haml::Engine.new(File.read 'test.haml')
engine.render(Object.new, { :@foo => 'abc', :@bar => '123' })
The reason that both of these examples are not working is that you are attempting to access instance variables from a different class. The simplest solution is to define and use methods instead of attempting to access another classes instance variables as if they were your own.
I.E. in test.rb
def foo
'abc'
end
test.haml
!!!
%h1 Testing HAML CLI
%p= foo
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With