`

关于Render在不同情况的用法

阅读更多
render是一个个人比较喜欢工具,先列一些常用的吧

render :action => "long_goal", :layout => "spectacular"
render :partial => "person", :locals => { :name => "david" }
render :template => "weblog/show", :locals => {:customer => Customer.new}
render :file => "c:/path/to/some/template.erb", :layout => true, :status => 404
render :text => "Hi there!", :layout => "special"
render :text => proc { |response, output| output.write("Hello from code!") }
render :xml => {:name => "David"}.to_xml
render :json => {:name => "David"}.to_json, :callback => 'show'
render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" }
render :js => "alert('hello')"
render :xml => post.to_xml, :status => :created, :location => post_url(post)


放到这里,用的时候好找,呵呵

Renders the content that will be returned to the browser as the response body.
Rendering an action

Action rendering is the most common form and the type used automatically by Action Controller when nothing else is specified. By default, actions are rendered within the current layout (if one exists).

  # Renders the template for the action "goal" within the current controller
  render :action => "goal"

  # Renders the template for the action "short_goal" within the current controller,
  # but without the current active layout
  render :action => "short_goal", :layout => false

  # Renders the template for the action "long_goal" within the current controller,
  # but with a custom layout
  render :action => "long_goal", :layout => "spectacular"

Rendering partials

Partial rendering in a controller is most commonly used together with Ajax calls that only update one or a few elements on a page without reloading. Rendering of partials from the controller makes it possible to use the same partial template in both the full-page rendering (by calling it from within the template) and when sub-page updates happen (from the controller action responding to Ajax calls). By default, the current layout is not used.

  # Renders the same partial with a local variable.
  render :partial => "person", :locals => { :name => "david" }

  # Renders the partial, making @new_person available through
  # the local variable 'person'
  render :partial => "person", :object => @new_person

  # Renders a collection of the same partial by making each element
  # of @winners available through the local variable "person" as it
  # builds the complete response.
  render :partial => "person", :collection => @winners

  # Renders a collection of partials but with a custom local variable name
  render :partial => "admin_person", :collection => @winners, :as => :person

  # Renders the same collection of partials, but also renders the
  # person_divider partial between each person partial.
  render :partial => "person", :collection => @winners, :spacer_template => "person_divider"

  # Renders a collection of partials located in a view subfolder
  # outside of our current controller.  In this example we will be
  # rendering app/views/shared/_note.r(html|xml)  Inside the partial
  # each element of @new_notes is available as the local var "note".
  render :partial => "shared/note", :collection => @new_notes

  # Renders the partial with a status code of 500 (internal error).
  render :partial => "broken", :status => 500

Note that the partial filename must also be a valid Ruby variable name, so e.g. 2005 and register-user are invalid.
Automatic etagging

Rendering will automatically insert the etag header on 200 OK responses. The etag is calculated using MD5 of the response body. If a request comes in that has a matching etag, the response will be changed to a 304 Not Modified and the response body will be set to an empty string. No etag header will be inserted if it‘s already set.
Rendering a template

Template rendering works just like action rendering except that it takes a path relative to the template root. The current layout is automatically applied.

  # Renders the template located in [TEMPLATE_ROOT]/weblog/show.r(html|xml) (in Rails, app/views/weblog/show.erb)
  render :template => "weblog/show"

  # Renders the template with a local variable
  render :template => "weblog/show", :locals => {:customer => Customer.new}

Rendering a file

File rendering works just like action rendering except that it takes a filesystem path. By default, the path is assumed to be absolute, and the current layout is not applied.

  # Renders the template located at the absolute filesystem path
  render :file => "/path/to/some/template.erb"
  render :file => "c:/path/to/some/template.erb"

  # Renders a template within the current layout, and with a 404 status code
  render :file => "/path/to/some/template.erb", :layout => true, :status => 404
  render :file => "c:/path/to/some/template.erb", :layout => true, :status => 404

Rendering text

Rendering of text is usually used for tests or for rendering prepared content, such as a cache. By default, text rendering is not done within the active layout.

  # Renders the clear text "hello world" with status code 200
  render :text => "hello world!"

  # Renders the clear text "Explosion!"  with status code 500
  render :text => "Explosion!", :status => 500

  # Renders the clear text "Hi there!" within the current active layout (if one exists)
  render :text => "Hi there!", :layout => true

  # Renders the clear text "Hi there!" within the layout
  # placed in "app/views/layouts/special.r(html|xml)"
  render :text => "Hi there!", :layout => "special"

Streaming data and/or controlling the page generation

The :text option can also accept a Proc object, which can be used to:

   1. stream on-the-fly generated data to the browser. Note that you should use the methods provided by ActionController::Steaming instead if you want to stream a buffer or a file.
   2. manually control the page generation. This should generally be avoided, as it violates the separation between code and content, and because almost everything that can be done with this method can also be done more cleanly using one of the other rendering methods, most notably templates.

Two arguments are passed to the proc, a response object and an output object. The response object is equivalent to the return value of the ActionController::Base#response method, and can be used to control various things in the HTTP response, such as setting the Content-Type header. The output object is an writable IO-like object, so one can call write and flush on it.

The following example demonstrates how one can stream a large amount of on-the-fly generated data to the browser:

  # Streams about 180 MB of generated data to the browser.
  render :text => proc { |response, output|
    10_000_000.times do |i|
      output.write("This is line #{i}\n")
      output.flush
    end
  }

Another example:

  # Renders "Hello from code!"
  render :text => proc { |response, output| output.write("Hello from code!") }

Rendering XML

Rendering XML sets the content type to application/xml.

  # Renders '<name>David</name>'
  render :xml => {:name => "David"}.to_xml

It‘s not necessary to call to_xml on the object you want to render, since render will automatically do that for you:

  # Also renders '<name>David</name>'
  render :xml => {:name => "David"}

Rendering JSON

Rendering JSON sets the content type to application/json and optionally wraps the JSON in a callback. It is expected that the response will be parsed (or eval‘d) for use as a data structure.

  # Renders '{"name": "David"}'
  render :json => {:name => "David"}.to_json

It‘s not necessary to call to_json on the object you want to render, since render will automatically do that for you:

  # Also renders '{"name": "David"}'
  render :json => {:name => "David"}

Sometimes the result isn‘t handled directly by a script (such as when the request comes from a SCRIPT tag), so the :callback option is provided for these cases.

  # Renders 'show({"name": "David"})'
  render :json => {:name => "David"}.to_json, :callback => 'show'

Rendering an inline template

Rendering of an inline template works as a cross between text and action rendering where the source for the template is supplied inline, like text, but its interpreted with ERb or Builder, like action. By default, ERb is used for rendering and the current layout is not used.

  # Renders "hello, hello, hello, again"
  render :inline => "<%= 'hello, ' * 3 + 'again' %>"

  # Renders "<p>Good seeing you!</p>" using Builder
  render :inline => "xml.p { 'Good seeing you!' }", :type => :builder

  # Renders "hello david"
  render :inline => "<%= 'hello ' + name %>", :locals => { :name => "david" }

Rendering inline JavaScriptGenerator page updates

In addition to rendering JavaScriptGenerator page updates with Ajax in RJS templates (see ActionView::Base for details), you can also pass the :update parameter to render, along with a block, to render page updates inline.

  render :update do |page|
    page.replace_html  'user_list', :partial => 'user', :collection => @users
    page.visual_effect :highlight, 'user_list'
  end

Rendering vanilla JavaScript

In addition to using RJS with render :update, you can also just render vanilla JavaScript with :js.

  # Renders "alert('hello')" and sets the mime type to text/javascript
  render :js => "alert('hello')"

Rendering with status and location headers

All renders take the :status and :location options and turn them into headers. They can even be used together:

  render :xml => post.to_xml, :status => :created, :location => post_url(post)

分享到:
评论
1 楼 fireflyman 2009-08-21  
基本全了,我收藏了.

相关推荐

    vue中render函数的使用详解

    但是,在特殊情况下,这种写死的模式无法满足需求,必须需要js的编程能力。此时,需要用render来创建HTML。 render方法的实质就是生成template模板; 通过调用一个方法来生成,而这个方法是通过render方法的参数...

    python-render用法.docx

    python-render用法全文共5页,当前为第1页。python-render用法全文共5页,当前为第1页。python render用法 python-render用法全文共5页,当前为第1页。 python-render用法全文共5页,当前为第1页。 Python Render是...

    Ruby的render_partial技术详解

    整理后的在Ruby on rails的Haml有关render_partial的用法,本资源为一张图

    Vue中render函数的使用方法

    什么情况下适合使用render函数 在一次封装一套通用按钮组件的工作中,按钮有四个样式(default success error )。首先,你可能会想到如下实现 &lt;div v-if=type&gt;success &lt;div v-else-if=type&gt;error &lt;div v-else...

    UGUI在不同RenderMode下的Canvas中的自适应方式

    在此基础上使用“GetWorldCorners”方法获取到的坐标的意义均不相同 2.使用“RectTransformUtility.ScreenPointToLocalPointInRectangle”,“Camera.xxCamera.ScreenToWorldPoint”等方式在不同空间中的坐标转换

    Offline Render v1.0 - Unity实时图像捕获插件 .rar

    离线render是一个容易使用的插件,realtime捕获方法的统一。它允许你捕获游戏视图到一个多通道openexr支持的注释,是最终的输出图像,但也有些共同的元素,每样深度,轻影、漫、澳(IFS的礼物进入现场作为一种形象...

    Vue.js render方法使用详解

    非使用render方法的情况 完整代码: &lt;!DOCTYPE html&gt; &lt;html&gt; &lt;head&gt; &lt;title&gt;Vue的render方法说明&lt;/title&gt; [removed][removed] &lt;/head&gt; &lt;body&gt; &lt;child level=1&gt;Hello world...

    turbolinks_render:在Rails控制器中通过Turbolink支持`render`

    turbolinks_render 在Rails控制器中使用render并通过Turbolinks处理响应。 Turbolinks开箱即用地支持 。 但是不支持render ,您必须使用。 该宝石旨在解决该问题。 我认为Turbolinks / Rails应该正式处理此问题。 ...

    对node.js中render和send的用法详解

    今天小编就为大家分享一篇对node.js中render和send的用法详解,具有很好的参考价值,希望对大家有所帮助。一起跟随小编过来看看吧

    JsRender for index循环索引用法详解

    主要介绍了JsRender for index循环索引用法,以实例形式详细分析了JsRender中循环的用法,需要的朋友可以参考下

    如何理解Vue的render函数的具体用法

    本文介绍了如何理解Vue的render函数的具体用法,分享给大家,具体如下: 第一个参数(必须) – {String | Object | Function} &lt;!DOCTYPE html&gt; &lt;html lang=en&gt; &lt;head&gt; &lt;meta charset=UTF-8&gt; ...

    koa-views-render:用于Koa和Lad的简单渲染(页面,本地)中间件(使用koa-views)

    目录安装 : npm install koa-views-render : yarn add koa-views-render用法这是一个简单的中间件,只需传递给ctx.render您提供的page和locals变量即可。 例如render(page,locals)将传递给ctx.render(page,locals)...

    Vue中render方法的使用详解

    主要为大家详细介绍了Vue中render方法的使用,具有一定的参考价值,感兴趣的小伙伴们可以参考一下

    博客Meteor.render源码

    博客 《Meteor.render 用法》 涉及到的代码

    element-ui table组件如何使用render属性的实现

    前言 起因: 在使用 element-ui table组件时,由于表列...用过 react 开发会经常用到 ant design ,其中它的 table 组件是可以接受 render属性的,下面使用table组件时,只需要定义好,columns(表头列) data(表的具体数

    react-lazy-render, 用于( 非常) 大型数据列表的延迟呈现.zip

    react-lazy-render, 用于( 非常) 大型数据列表的延迟呈现 响应迟缓呈现用于( 非常) 大型数据列表的延迟呈现演示工具特性仅渲染可见子对象使用起来非常简单BYOC - 带你自己的子组件安装使用反应的最简单方法是从NPM...

    extjs render 用法介绍

    代码如下: var cm = new Ext.grid.ColumnModel( [ new Ext.grid.RowNumberer({ header: “”, width: 20, align: ‘center’ }), { header: ”, align: ‘center’, dataIndex: ‘AccountAndRoseID’, width: 50, ...

Global site tag (gtag.js) - Google Analytics