如何将erubi模板渲染为html?

时间:2017-10-03 09:58:58

标签: ruby erb

当rails 5.1+切换到erubi时,我尝试在ruby脚本中使用它:

require 'erubi'

template = Erubi::Engine.new("<%= test %>", escape: true)

但是我试图将该模板渲染为html。

erubi源代码:https://github.com/jeremyevans/erubi


erubierubis的分支,而在erubis中,渲染是通过result方法完成的:

require 'erubis'

template = Erubis::Eruby.new("<%= test %>", escape: true)
template.result test: "<br>here" #=> "&lt;br&gt;here"

result中没有erubi方法。

2 个答案:

答案 0 :(得分:1)

From the Erubi README(它表示“对于文件”,但它似乎表示“对于模板”):

  

Erubi仅内置支持检索文件的生成源:

require 'erubi'
eval(Erubi::Engine.new(File.read('filename.erb')).src)

因此,您需要使用其中一个eval变体从独立脚本运行。

template = Erubi::Engine.new("7 + 7 = <%= 7 + 7 %>")
puts eval(template.src)

输出7 + 7 = 14

如果您希望能够在Rails,Sinatra等中使用模板中的实例变量,则需要创建上下文对象并使用instance_eval

class Context
  attr_accessor :message
end

template = Erubi::Engine.new("Message is: <%= @message %>")
context = Context.new
context.message = "Hello"

puts context.instance_eval(template.src)

输出Message is: Hello

答案 1 :(得分:1)

在rails 5.1中,我将Erubis::Eruby.new代码切换为以下代码:

ActionController::Base.render(inline: "<%= test %>", locals: {test: "<br>here"})

铁轨将为您带来沉重的负担。

相关问题