0

我有一个控制器,我想从中将文本呈现到 /views/test/index.html.erb:

class TestController < ApplicationController
  def index
    if testStuff() do
      <render text to view>
    end
  end

  private 
  testStuff()
    return true
  end
end

最简单的方法是什么?感谢您的回答!

4

4 回答 4

0

在执行控制器 rails 的方法 index 后,将尝试加载名称为 index.html.erb 的视图(或您使用的任何其他模板)。您可以在索引中声明一个成员,并且该成员将可用于视图,例如:

def index
  @text = "Hello world!"
end

那么在你看来:

...
<span><%= @text %></span>
...

如果您的 @text 变量具有您信任的 html,则在您的视图中使用 @text.html_safe。

于 2013-04-18T11:36:56.783 回答
0

尝试将文本分配给实例变量。喜欢:

class TestController < ApplicationController
  def index
    if testStuff() do
      @text = "Text what you want to render"
    end
  end

在视图中:

<%= @text %>
于 2013-04-18T11:39:02.947 回答
0

你可以像这样渲染为json

def index
    if testStuff() do
     @category_lists = CategoryList.get_categories(current_user.id)

     respond_to do |format|
       format.html # index.html.erb
       format.json { render json: @category_lists }
     end
    end
  end
于 2013-04-18T11:39:12.373 回答
0

虽然不好,但您可以将测试移至视图:

class TestController < ApplicationController
  helper_method :is_test?      

  def index
  end

  private 

  def is_test?
    return true
  end
end

然后在视图中:

<% if is_test? %>
  <span>Some text here</span>
<% end %>
于 2013-04-18T11:51:04.460 回答