rails render

来源:互联网 发布:阿里云oss下载文件 编辑:程序博客网 时间:2024/06/08 18:48
载入模板文件


# 载入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<br>
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
think in coding