技术笔记:rubyonrails中render的使用

简介: 技术笔记:rubyonrails中render的使用

最近写ror,因为比较菜,很多东西不知道,只能看一点查一点了


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 => "", :locals => { :name => "david" }


render :js => "alert('hello')"


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


例如 就是 跳转到 _form.html.erb文件


1:render(:text => string)


2:render(:inline => string,


3:【:type => "rhtml"|"rxml"】)


4:render(:action => action_name)


5:render(:file => path,


6:【:use_full_path => true|false】)


7:render(:template => name)


8:render(:partial => name)


9:render(:nothing=>true)


10:render()


第1行:直接渲染出文本


第2行:把传入的string渲染成模板(rhtml或者rxml)


第3行:直接调用某个action的模板,相当于forward到一个view


第4行:使用某个模板文件render, 当use_full_path参数为true时可以传入相对路径


第5行:使用模板名render,e.x.: render(:template => "blog/short_list")


第6行:以局部模板渲染


第7行:什么也不输出,包括layout


第8行:默认的的render, 相当于render(:action => self)


查了render的源码,粘贴出来如下:


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 //代码效果参考:http://www.jhylw.com.cn/054338567.html

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 'David'


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 'David'


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 //代码效果参考:http://www.jhylw.com.cn/335129431.html

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 => ""


# Renders "


Good seeing you!


" using Builder


render :inline => "xml.p { 'Good seeing you!' }", :type => :builder


# Renders "hello david"


render :inline => "", :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)

相关文章
|
9月前
|
人工智能 自然语言处理 Cloud Native
大型企业如何建设BI系统?2026年企业级BI系统建设方案与实施路径
2026年,数据成为大型企业核心生产要素。面对跨地域、多业态、海量异构数据挑战,传统BI已难支撑实时决策与业务敏捷性。瓴羊Quick BI以云原生架构、AI增强分析(自然语言查询、自动归因)、企业级安全管控及本土化复杂报表能力,助力企业构建高效、智能、可落地的商业智能系统,加速数据价值变现。(239字)
|
9月前
|
存储 人工智能 JavaScript
OpenClaw阿里云+本地部署省Token秘籍;+Memos插件 Token 消耗直降77%
使用OpenClaw时,Token消耗过高是用户最核心的痛点——每次对话都需携带完整历史记录,重复信息占用大量Token,长期使用成本居高不下。而Memos作为一款轻量记忆优化插件,通过“智能提取关键信息+按需召回+避免重复传输”三大机制,能将Token消耗降低77%以上,完美解决OpenClaw“烧钱”问题。
2373 3
|
运维 Kubernetes 安全
评测文章:阿里云容器服务ACK
阿里云容器服务(Alibaba Cloud Container Service for Kubernetes,简称 ACK)是一个全托管的 Kubernetes 容器管理服务。它可以帮助企业在云上高效地部署、管理和扩展容器化应用。本文将详细评测 ACK 的功能、优势及其应用场景,帮助读者更好地理解和使用这一服务。
|
JSON 前端开发 安全
【潜意识java】前后端跨域问题及解决方案
本文深入探讨了跨域问题及其解决方案。跨域是指浏览器出于安全考虑,限制从一个域加载的网页请求另一个域的资源。
4930 0
|
1天前
|
监控 网络协议 算法
2026年起SSL证书有效期逐年缩短:企业如何避免“续期风暴”!
SSL证书有效期将从2026年起分三阶段逐步缩短至47天,人工续期难以为继。阿里云“WoSign SSL证书+自动化服务”,支持域名监控、自动托管、云产品/服务器一键部署及智能提醒,助力企业高效应对高频续期挑战。
8050 2
|
10天前
|
域名解析 人工智能 Linux
|
20天前
|
Linux Go 开发工具
手机上跑 DeepSeek 智能体:开源安卓客户端 DSH Go 安装与使用指南
DSH Go 是一款开源安卓客户端,将 DeepSeek Harness 智能体引擎装进手机:免 Root、免 Termux,一键安装即用;支持本机运行(内置 Ubuntu+Node.js)或远程接管电脑会话;具备插话打断、过程折叠、屏幕操控、端到端加密分享等特色功能,真正实现智能体“口袋化”。
18134 63
|
18天前
|
人工智能
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置
进不去 Antigravity 或 Gemini,提示所在地区不可用?三步查清 Google 账号关联地区、官方更正表单理由选法与改区注意事项。
Google 提示「所在地区不可用」?进不去 Antigravity 或 Gemini,先查账号这个设置