Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I pass instance variables to a HAML template on the command line?

Background

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.

Requiring a Ruby File

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>

Programmatic Attempt

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.

Restating the Question

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?

like image 739
Todd A. Jacobs Avatar asked Apr 15 '13 22:04

Todd A. Jacobs


2 Answers

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' })
like image 62
Zach Kemp Avatar answered Sep 25 '22 21:09

Zach Kemp


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
like image 36
Alex.Bullard Avatar answered Sep 22 '22 21:09

Alex.Bullard