[ruby] rails render

weixin_34292959發表於2012-05-25

載入模板檔案

# 載入app/views/<controllername>/edit.html.erb
render :edit
render :action => :edit
render 'edit'
render 'edit.html.erb'
render :action => 'edit'
render :action => 'edit.html.erb'

# 載入app/views/books/edit.html.erb
render 'books/edit'
render 'books/edit.html.erb'
render :template => 'books/edit'
render :template => 'books/edit.html.erb'
render '/path/to/rails/app/views/books/edit'
render '/path/to/rails/app/views/books/edit.html.erb'
render :file => '/path/to/rails/app/views/books/edit'
render :file => '/path/to/rails/app/views/books/edit.html.erb'

String Template

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

Text Output

render :text => "OK"

JSON Output

render :json => @product

XML Output

render :xml => @product

Javasctipt Output

render :js => "alert('Hello Rails');"

 

content_type(文字頭)

# text/html(default) | application/json | application/xml | application/rss
render :file => filename, :content_type => 'application/rss'

 

layout

# 使用app/views/layouts/special_layout.html.erb
# 預設使用 app/views/layouts/<controllername>.html.erb
render :layout => 'special_layout'
# no layout
render :layout => false  

Specifying Layouts for Controllers

# 定義整個controller的layout
class ProductsController < ApplicationController
  layout "inventory"
  #...
end

Choosing Layouts at Runtime

class ProductsController < ApplicationController
  layout :products_layout
 
  def show
    @product = Product.find(params[:id])
  end
 
  private
    def products_layout
      @current_user.special? ? "special" : "products"
    end
 
end

Conditional Layouts

class ProductsController < ApplicationController
  layout "product", :except => [:index, :rss]
end

 

輸出Http狀態

# http 狀態
render :status => 500
render :status => :forbidden

 

location重定向

render :xml => photo, :location => photo_url(photo)

 

跳轉

# 跳轉到指定地址
redirect_to photos_url
# 後退
redirect_to :back
# 301重定向到指定地址
redirect_to photos_path, :status => 301

相關文章