rails 3 自定义 mime 类型 - 默认视图格式 [英] rails 3 custom mime type - default view format

查看:17
本文介绍了rails 3 自定义 mime 类型 - 默认视图格式的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要渲染一些没有布局的视图.要跳过行 :render :layout=>false 和 if else 来自控制器操作的逻辑,我有自定义 mime 类型,如 phtml(纯 html).

I need to render some views without layout. To skip line :render :layout=>false and if else logic from controller actions, i have custom mime type like phtml (plain html).

Mime::Type.register "text/phtml", :phtml

这种格式需要渲染相同的 html 视图,但只是没有布局.我用 app.js 中的这段代码完成了这个.控制器:

this format need to render the same html views, but only without layout. I complete this with this chunk of code in app. controller:

 before_filter proc { |controller|
  if params[:format] && params[:format]=='phtml'
    controller.action_has_layout = false
    controller.request.format    = 'html'

  end
  }

首先,这很难看,其次我无法再从控制器中控制这种格式:

First, this is ugly, second i can't any more control this format from controller in the way:

respond_to :phtml,:only=>:index

因为它总是以请求的 phtml 格式呈现视图.有更好的解决方案吗?例子?如何为视图格式设置别名?

because it will always render view with requested format phtml. is there a better solution? example? how can i alias view formats?

非常感谢

推荐答案

我还没有找到更好的解决方案,只更新到我之前的例子:

I haven't found better solution,only update to my previous example:

 before_filter proc { |controller|
    if params[:format] && params[:format]=='plain_html' && controller.collect_mimes_from_class_level.include?(:plain_html)
      controller.action_has_layout = false
      controller.request.format    = 'html'
    end
  }

我添加了这一行来检查我们控制器中定义的新格式:

i added this line to check is a new format defined into our controller:

controller.collect_mimes_from_class_level.include?(:plain_html)

现在我们可以拥有全新的格式,它将呈现我们的标准 html 视图,而不是为新格式构建新视图.

Now we can have full new format which will render our standard html vews rather the build new views for the new format.

如果我们不想共享现有的 html 代码,而是根据请求的格式构建不同的逻辑,这将很有用.

This can be useful if we wont to share existing html code, but build different logic based on requested format.

例如,我们可以轻松地准备要打印的 html 内容,例如:

For example, we can easily prepare our html content for print like:

class PagesController < ActionController::Base

layout 'print',:only=>:show
respond_to :plain_html,:only=>[:show]

  def show
    Page.find(1)
    respond_with @page
  end
end

请求会是这样的:

http://www.example.com/pages/1.plain_html

我希望有人会觉得这很有用.

I hope that someone will find this useful.

如果你有更好的方法来做到这一点,请与我们分享.

If u have a better approach for doing this, please share with us.

问候

这篇关于rails 3 自定义 mime 类型 - 默认视图格式的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆