为什么这个ERB独立渲染不适用于实例变量

时间:2012-03-16 04:26:09

标签: ruby-on-rails ruby erb

为什么这个ERB独立渲染不适用于实例变量?也就是说,“<%= @test_var%>”的输出为空白线?

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

和email.erb

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

给出

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

</body>
</html>

4 个答案:

答案 0 :(得分:2)

找到答案......需要

(a)我的班级中的以下实例变量是:

  # Support templating of member data.
  def get_binding
    binding
  end

(b)当在ERB对象上调用“run”时必须传递此方法的结果,例如

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

答案 1 :(得分:1)

今天正在处理类似的事情。这就是我开始工作的方式:

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})

希望这有帮助!

答案 2 :(得分:0)

试试这个

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

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

答案 3 :(得分:0)

您需要将绑定上下文传递给模板,您的代码应该是

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