How to Render a String as an Erb File

How to render erb template to string inside action?

If you only need the rendered HTML, and don't need any functionality from the controller, you might try using ERB directly within a helper class, eg.:

module FaxHelper

def to_fax
html = File.open(path_to_template).read
template = ERB.new(html)
template.result
end

end

The ERB docs explain this in more detail.

EDIT

To get the instance variables from the controller, pass the binding into the result call, eg:

# controller
to_fax(binding)

# helper class
def to_fax(controller_binding)
html = File.open(path_to_template).read
template = ERB.new(html)
template.result(controller_binding)
end

Note: I've never done this, but it seems workable :)

How to render a string as an erb file?

If I properly understand you, this would be helpful:

require 'erb'
str = "Hello <%= 'World'%>"
result = ERB.new(str).result # => "Hello World"

UPDATE

If you want to use variables:

require 'erb'
w = "World"
str = "Hello <%= w %>"
result = ERB.new(str).result(binding) # => "Hello World"

How to insert string into an erb file for rendering in rails 3.2?

I think i got your question.
you can append any html string in erb using
in view:

<%= render inline:"<p>new Field</p>"%>

or

<%= render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>" %>

or
in controller as:

render inline: "<% products.each do |p| %><p><%= p.name %></p><% end %>"

writing it in any _xyz.html.erb or xyz.html.erb and also can be used from controller, as well. for more check following link. in sub topic - 2.2.6 Using render with :inline.
rails guide

I have checked working of this. Let me know in case of any issue.

Render %= % as a String in an .html.erb View?

You should double the % symbols as follow:

<h3><%%= rating_color %></h3>

Edit for source:

In erb.rb line 50, we see that <%% is a special tag that is replaced by <% we can also see that on line 650.

Rails 4: render ERB from database into string

You need to tell render to use a text string, not a template.

rendered = render_to_string(:text => MailTemplate.find(1).body)

http://api.rubyonrails.org/classes/ActionView/Helpers/RenderingHelper.html#method-i-render

ERB render expression as string

Short answer is no. You either:

  1. replace < and > with the equivalent html codes < and >, which looks like <% unsubscribe %>,

or


  1. make your ruby statement print the string: <%= '<% subscribe %>' %>

How to render js.erb file in a string for Rails 3.2?

Yeah your js.erb should work fine as long as your not mixing in html as well. You can use this to turn it into a string:

erb  = ERB.new("js_erb_code")
render erb.result

How to render ERB view as string?

render erb for pdf you could try render_to_string



Related Topics



Leave a reply



Submit