简体   繁体   中英

Render text from controller to view

I have a controller from which I want to render text to /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

What is the easiest way to do this? Thanks for an answer!

After executing the method index of the controller rails will try to load a view with name index.html.erb (or any other template you use). You may declare a member in index and that member will be available to the view, ex:

def index
  @text = "Hello world!"
end

Then in your view:

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

If your @text variable has html you trust then use @text.html_safe in your view.

try to assign text into a Instance Variable. Like:

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

at view:

<%= @text %>

You can render as json like this

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

Although it is not good, you can move you test to the view:

class TestController < ApplicationController
  helper_method :is_test?      

  def index
  end

  private 

  def is_test?
    return true
  end
end

And then in view:

<% if is_test? %>
  <span>Some text here</span>
<% end %>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM