Ruby-on-rails local_assigns 在 Rails 中是如何工作的?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/10819189/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:28:25  来源:igfitidea点击:

How does local_assigns work in Rails?

ruby-on-railsviews

提问by Lee McAlilly

I've been googling around about this and can't find the right path. I'm working on a Rails app that is using a method called local_assigns. This appears to be something in Rails or a gem, and not specific to my app, but it's used for rendering a partial in different contexts, such as this:

我一直在谷歌上搜索这个,但找不到正确的路径。我正在开发一个使用名为 local_assigns 的方法的 Rails 应用程序。这似乎是 Rails 或 gem 中的东西,并不特定于我的应用程序,但它用于在不同的上下文中呈现部分,例如:

<% if local_assigns[:custom_name] %>
  <li><%= custom_name %></li>
<% else %>

or also this:

或者这个:

<%= render "discussions/complementary/#{local_assigns[:action] || params[:action]}" %>

Is this is Rails method? Where can I find more documentation about this?

这是 Rails 方法吗?我在哪里可以找到更多关于此的文档?

回答by Chamnap

local_assignsis a Rails view helper method that you can check whether this partial has been provided with local variables or not.

local_assigns是一个 Rails 视图助手方法,您可以检查此部分是否已提供局部变量。

Here you render a partial with some values, the headlineand personwill become accessible with predefined value.

在这里,您使用一些值渲染部分,headlineperson将通过预定义的值变得可访问。

<%= render "shared/header", { :headline => "Welcome", :person => person } %>

In shared/headerview:

shared/header视图:

Headline: <%= headline %>
First name: <%= person.first_name %>

Here is how you check these variables has passed in or not:

以下是检查这些变量是否传入的方法:

<% if local_assigns.has_key? :headline %>
  Headline: <%= headline %>
<% end %>

Check this document for more detail on the section Passing local variables to sub templates.

有关将局部变量传递给子模板部分的更多详细信息,请查看此文档。