gpt4 book ai didi

ruby-on-rails - Rails 3,将局部变量传递给部分

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

这个问题在这里已经有了答案:




8年前关闭。




Possible Duplicate:
Rails: confused about syntax for passing locals to partials



我想将局部变量(模型中没有相关字段)传递给部分变量。
# infos/index.html.erb

<%= render :partial => 'info', :locals => {:info => first, :img_style => "original"} %>

:img_style 将是图像的 html 样式。
# infos/_info.html.erb
<% first = @infos.shift %>
<%= image_tag(info.image.url, :class => img_style), info %>
# and here goes code for normal iteration
<% @infos.each do |e| %>
# etc

但它不起作用,它返回错误:
# GET /infos/
undefined local variable or method `img_style' for #<#<Class:0xc471f34>:0xc470cc4>

可以在不制作多余部分的情况下完成吗?

对不起我的英语不好。 :P

编辑:

那么模型信息没有 :img_style 字段
# db/schema.rb
create_table "infos", :force => true do |t|
t.string "title"
t.text "description"
t.integer "place_id"
t.datetime "created_at"
t.datetime "updated_at"
t.string "image_file_name"
t.string "image_content_type"
t.integer "image_file_size"
t.datetime "image_updated_at"
t.text "short"
end

EDIT2:

再简单不过
<%= img_style %>

不工作。

应用程序堆栈跟踪
app/views/infos/_info.html.erb:3:in `_app_views_infos__info_html_erb___1029249744_92158380_1472718'
app/views/infos/index.html.erb:7:in `_app_views_infos_index_html_erb__184644561_92172050_0'
app/controllers/infos_controller.rb:8:in `index'

EDIT3:

观看次数
# infos/index.html.erb
<div >
<h1><%= t('info.infos') %></h1>
<div id="left">
<% first = @infos.shift %>
<div>
<% @aimg_style = "original"%>
<%= render 'info', :locals => {@img_style => @aimg_style } %>
</div>
<ul>
<% @infos.each do |e| %>
<li>
<div>
<%= render :partial => 'info', :object => e %>
</div>
</li>
<% end %>
</ul>
<%= will_paginate @infos %>
# infos/_info.html.erb
<%#= link_to thumbnail(info, "listTabsImg", false, img_style), info %>
<%#= image_tag(info.image.url()) %>
<%= img_style %>
<p>
<strong class="nameBox"><%= link_to info.title, info %></strong>
<span><%= info.short %>...</span>
<%= link_to "#{t('more')} »", info %>
</p>

终于

这不起作用:
# infos/index.html.erb
<% first = @infos.shift %>
<div class="boxEvent">
<% @aimg_style = "original"%>
<%= first %>
<%= render 'info', :locals => {:info => first, :img_style => @aimg_style } %>
</div>

这有效:
# infos/index.html.erb
<% @infos.each do |e| %>
<li>
<div class="boxEvent">
<%= render :partial => 'info', :locals => {:info => e, :img_style => "original"} %>
</div>
</li>
<% end %>

有人知道为什么吗?

最佳答案

我实际上只是在 Rails 3 中使用这种语法:

render "a_partial", :a_local_variable => whatever, :another_variable => another

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

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