2

I'm trying to render HTML from an ERB object within a controller (the ERB object is stored in the DB), but with no success.

I would like to do something like this:

First, I created a Func instance:

Func.Create(text: "<% @users.each do |user| %>
                   <td><%= user.id %></td>
                   <td><%= link_to user.username, user_path(user) %></td>")

Then, in the controlller:

class MainController < ApplicationController
  def foo
    @users = User.all
    render :html  => bar(binding) 
  end

  def bar(controller_binding)
    html =  Func.find(1)
    template = ERB.new(html.text)
    template.result(controller_binding)
  end
end

But all I get are errors, like this:

"Missing template main/resource_name, application/resource_name with
  {:locale=>[:en], :formats=>[:html], :handlers=>[:erb, :builder, :raw, :ruby, 
  :jbuilder, :coffee]}. Searched in: * "c:/Users/david/sample/app/views""

and

"(erb):3: syntax error, unexpected $end, expecting keyword_end ...
  ut.force_encoding(__ENCODING__) ... ^"
0

2 Answers 2

1

Replace

Func.Create(text: "<% @users.each do |user| %>
                   <td><%= user.id %></td>
                   <td><%= link_to user.username, user_path(user) %></td>")

with

    Func.Create(text: "<% if @users.nil? %>
              <p> There are no users in database </p>
            <% else %>          
              <% @users.each do |user| %>
                   <td><%= user.id %></td>
                   <td><%= link_to user.username, user_path(user) %></td><% end %> <% end %>")

<% end %> end of block was missing.

Also, replace render :html => bar(binding) with render :inline => bar(binding)

You could also shorten your code as below,

  def foo
    @users = User.all
    html =  Func.find(1)
    render :inline  => html.text
  end
4
  • You absolutely right, I changed it, and now I'm get this error: "undefined method `each' for nil:NilClass".. how to forward @users variable to bar ?
    – David
    Mar 5, 2014 at 20:28
  • Sorry, I don't think you have chat access. Check if you have users present in the database.
    – Kirti Thorat
    Mar 5, 2014 at 20:34
  • Try the updated Func.create which will not throw error, if users are not existing.
    – Kirti Thorat
    Mar 5, 2014 at 20:39
  • Great, It work like a charm.. 10X ! So inline actually replace html and include its all functionality ?
    – David
    Mar 5, 2014 at 20:50
0

You shouldn't doing that in the controller. Not sure what you're trying to accomplish but it looks like a helper may be more appropriate.

1
  • I'm trying to store the html code in DB in order to keep it dynamic. Do you think helper is better for this purpose? If so, can you explain how to render an html from helper?
    – David
    Mar 5, 2014 at 20:11

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.