gpt4 book ai didi

ruby-on-rails - Rails 4 - 将变量传递给部分

转载 作者:行者123 更新时间:2023-12-03 04:38:37 26 4
gpt4 key购买 nike

我正在学习 Ruby on Rails 教程,并在尝试将变量传递给部分时遇到问题。

我的_user部分如下

<li>
<%= gravatar_for user, size: 52 %>
<%= link_to user.name, user %>
</li>

我想传递一个数字作为大小值。我尝试如下但没有任何运气。

<%= render @users, :locals => {:size => 30} %>

最佳答案

来自 PartialRender 上的 Rails api :

Rendering the default case

If you're not going to be using any of the options like collections or layouts, you can also use the short-hand defaults of render to render partials.

示例:

# Instead of <%= render partial: "account" %>
<%= render "account" %>

# Instead of <%= render partial: "account", locals: { account: @buyer } %>
<%= render "account", account: @buyer %>

# @account.to_partial_path returns 'accounts/account', so it can be used to replace:
# <%= render partial: "accounts/account", locals: { account: @account} %>
<%= render @account %>

# @posts is an array of Post instances, so every post record returns 'posts/post' on `to_partial_path`,
# that's why we can replace:
# <%= render partial: "posts/post", collection: @posts %>
<%= render @posts %>

因此,您可以使用传递局部变量 size 来渲染,如下所示:

<%= render @users, size: 50 %>

然后在_user.html.erb部分中使用它:

<li>
<%= gravatar_for user, size: size %>
<%= link_to user.name, user %>
</li>

请注意,size: size 相当于 :size => size

关于ruby-on-rails - Rails 4 - 将变量传递给部分,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/16242121/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com