加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

ruby-on-rails – Rails 3使用自定义模板响应

发布时间:2020-12-16 21:13:40 所属栏目:百科 来源:网络整理
导读:我的控制器中有最新动作.此操作只是抓取最后一条记录并呈现显示模板. class PicturesController ApplicationController respond_to :html,:json,:xml def latest @picture = Picture.last respond_with @picture,template: 'pictures/show' endend 是否有更
我的控制器中有最新动作.此操作只是抓取最后一条记录并呈现显示模板.
class PicturesController < ApplicationController
  respond_to :html,:json,:xml

  def latest
    @picture = Picture.last

    respond_with @picture,template: 'pictures/show'
  end
end

是否有更清洁的方式来提供模板?似乎冗余必须提供HTML格式的图片/部分,因为这是Sites控制器.

解决方法

如果要渲染的模板属于同一个控制器,则可以像这样编写:
class PicturesController < ApplicationController
  def latest
    @picture = Picture.last

    render :show
  end
end

图片/路径没有必要.你可以在这里深入探讨:Layouts and Rendering in Rails

如果需要保留xml和json格式,可以执行以下操作:

class PicturesController < ApplicationController
  def latest
    @picture = Picture.last

    respond_to do |format|
      format.html {render :show}
      format.json {render json: @picture}
      format.xml {render xml: @picture}
    end

  end
end

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读