简体   繁体   English

Rails从application.html.erb渲染实例变量

[英]Rails rendering instance variable from 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. 我正在使用Rails 4书来关注敏捷Web开发,我对渲染方面有点困惑。 The simple version of the question is... within the application.html.erb file there it says 这个问题的简单版本是...在application.html.erb文件中

render @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. 这很令人困惑,因为我认为需要有一个与该视图相关联的控制器才能知道要使用哪个部分和@cart变量。 Is it simply by naming convention that this line looks for a partial like _cart.html.erb? 是否只是通过命名约定,该行寻找像_cart.html.erb这样的部分? And in that case does it not actually know what @cart is until it renders that partial? 在那种情况下,它实际上不知道@cart是什么,直到它呈现部分?

Some clarification would be lovely. 一些澄清会很可爱。 Thanks! 谢谢!

This is a shorthand syntax. 这是一种简写语法。 From the docs : 来自文档

Every partial also has a local variable with the same name as the partial (minus the underscore). 每个partial也有一个局部变量,其名称与partial(减去下划线)相同。 You can pass an object in to this local variable via the :object option: 您可以通过:object选项将对象传递给此局部变量:

<%= render partial: "customer", object: @new_customer %>

Within the customer partial, the customer variable will refer to @new_customer from the parent view. 在customer partial中,customer变量将从父视图引用@new_customer。

If you have an instance of a model to render into a partial, you can use a shorthand syntax: 如果要将模型实例渲染为局部,则可以使用简写语法:

<%= render @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. 假设@customer实例变量包含Customer模型的实例,这将使用_customer.html.erb来呈现它,并将局部变量customer传递给partial,这将引用父视图中的@customer实例变量。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM