来自application.html.erb的Rails渲染实例变量 [英] Rails rendering instance variable from application.html.erb
问题描述
我正在学习《用Rails开发敏捷Web开发4》一书,在渲染方面我有些困惑.这个问题的简单版本是...在application.html.erb文件中,它显示为
I am following the Agile Web Development with Rails 4 book and I'm a bit confused on a part about rendering. The simple version of the question is... within the application.html.erb file there it says
render @cart
这令人困惑,因为我认为需要与该视图关联的控制器才能知道要使用哪个局部变量和@cart变量.是否仅通过命名约定就可以使该行查找类似于_cart.html.erb的部分?在那种情况下,直到它呈现部分内容时,它才真正知道@cart是什么吗?
This is confusing because I thought that there needed to be a controller associated with that view in order to know which partial and @cart variable to use. Is it simply by naming convention that this line looks for a partial like _cart.html.erb? And in that case does it not actually know what @cart is until it renders that partial?
进行一些澄清将是很可爱的.谢谢!
Some clarification would be lovely. Thanks!
推荐答案
这是一种简写语法. 从文档中:
This is a shorthand syntax. From the docs:
每个局部变量都有一个与局部变量同名的局部变量(减去下划线).您可以通过:object选项将一个对象传递给此局部变量:
Every partial also has a local variable with the same name as the partial (minus the underscore). You can pass an object in to this local variable via the :object option:
<%= render partial: "customer", object: @new_customer %>
在customer部分中,customer变量将从父视图中引用@new_customer.
Within the customer partial, the customer variable will refer to @new_customer from the parent view.
如果您有模型的实例可以呈现为局部模型,则可以使用简写语法:
If you have an instance of a model to render into a partial, you can use a shorthand syntax:
<%= render @customer %>
假设@customer实例变量包含Customer模型的实例,它将使用_customer.html.erb呈现它,并将局部变量customer传递给局部变量,该局部变量将引用@customer实例变量.父视图.
Assuming that the @customer instance variable contains an instance of the Customer model, this will use _customer.html.erb to render it and will pass the local variable customer into the partial which will refer to the @customer instance variable in the parent view.
这篇关于来自application.html.erb的Rails渲染实例变量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!