我有一个模板,其中包含用于渲染的各种变量。
有没有一种方法可以毫无异常(exception)地在模板中呈现特定变量。
e.g. template_content = "My name is <%=firstname%>. I live at <%=location%>"
variable_hash = {firstname: "eric"}
Erubis::Eruby.new(template_content).result(variable_hash)
预期输出:
"My name is eric. I live at <%=location%>"
我的用例是使用第一个变量进行渲染并获取渲染的内容。
然而,当我运行上面的代码时,它给出了异常:
“未定义的局部变量或方法 location
”
我正在使用 Erubis 进行渲染。我也很喜欢 ERB 渲染。只需要用 ruby 脚本渲染。
有什么办法让它起作用吗?
最佳答案
module MyModule
def method_missing(method_name)
super
rescue NameError => e
return method_name
end
end
eb = Erubis::Eruby.new('My name is <%=firstname%>. I live at <%=location%>')
eb.extend(MyModule)
result = eb.result(:firstname =>'Ab')
puts result
不确定这是否是一个好的解决方案,可能有更好的解决方案。
关于ruby-on-rails - Ruby 渲染特定变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/28407225/