Greg
Greg

Reputation: 34798

why doesn't this ERB standalone rendering work for the instance variable

why doesn't this ERB standalone rendering work for the instance variable? That is the output is blank for the "<%= @test_var %>" line?

@test_var = "test variable"
template = Tilt.new('./app/scripts/email.erb')
st = template.render
puts st

and email.erb

<html>
<body>
  <h1>This is it!</h1>
  <p>
      Phone Number: <%= @test_var %>
  </p>
</body>
</html>

gives

<html>
<body>
  <h1>This is it!</h1>
  <p>
   Phone Number:
  </p>

</body>
</html>

Upvotes: 1

Views: 1440

Answers (4)

Ismael
Ismael

Reputation: 16720

Try this

test_var = "test variable"
template = Tilt.new('./app/scripts/email.erb')
st = template.render(self, test_var: test_var)
puts st

and

<html>
<body>
  <h1>This is it!</h1>
  <p>
      Phone Number: <%= test_var %>
  </p>
</body>
</html>

Upvotes: 0

Damian Hamill
Damian Hamill

Reputation: 1

You need to pass the binding context to the template, your code should be

@test_var = "test variable"
template = Tilt.new('./app/scripts/email.erb')
st = template.render(self)
puts st

Upvotes: 0

innonate
innonate

Reputation: 159

Was just working on something similar today. This is how I got it to work:

template = File.read("path/to/template.html.erb").gsub(/^  /, '')
rhtml = ERB.new(template)
@hash_of_all_i_need_in_template = method_to_get_hash_of_all_i_need_in_template
email_contents = rhtml.result(Proc.new{@hash_of_all_i_need_in_template})

Hope this helps!

Upvotes: 1

Greg
Greg

Reputation: 34798

found the answer...need to have

(a) the following in my class where the instance variables are:

  # Support templating of member data.
  def get_binding
    binding
  end

(b) also when calling "run" on the ERB object have to pass the result from this method, e.g.

rhtml = ERB.new(erb_str)
html = rhtml.run(get_binding)

Upvotes: 2

Related Questions