Frage

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__) ... ^"
War es hilfreich?

Lösung

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

Andere Tipps

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.

Lizenziert unter: CC-BY-SA mit Zuschreibung
Nicht verbunden mit StackOverflow
scroll top