Reputation: 13487
As rails 5.1+ switched to erubi
I tried to use that in ruby script:
require 'erubi'
template = Erubi::Engine.new("<%= test %>", escape: true)
However I'm stacked trying to render that template to html.
erubi
source code: https://github.com/jeremyevans/erubi
erubi
is fork of erubis
, and in erubis
the rendering is done via result
method:
require 'erubis'
template = Erubis::Eruby.new("<%= test %>", escape: true)
template.result test: "<br>here" #=> "<br>here"
However there's no result
method in erubi
.
Upvotes: 5
Views: 738
Reputation: 367
In rails 5.1 I switched out the Erubis::Eruby.new
code to the following:
ActionController::Base.render(inline: "<%= test %>", locals: {test: "<br>here"})
Rails will do the heavy lifting.
Upvotes: 1
Reputation: 79803
From the Erubi README (it says “for a file” but it appears to mean “for a template”):
Erubi only has built in support for retrieving the generated source for a file:
require 'erubi' eval(Erubi::Engine.new(File.read('filename.erb')).src)
So you will need to use one of the eval
variants to run from a standalone script.
template = Erubi::Engine.new("7 + 7 = <%= 7 + 7 %>")
puts eval(template.src)
Outputs 7 + 7 = 14
.
If you want to be able to use instance variables in your template as you might be used to from Rails, Sinatra etc., you will need to create a context object and use 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)
Outputs Message is: Hello
.
Upvotes: 4