我想将局部变量(模型中没有相关字段)传递给partial。
# 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
编辑2:
即使简单
<%= img_style %>
don't works.
Application Stack Trace
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'
编辑3:
视图
# 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 %>
有人知道为什么吗?
<%= image_tag
是否放置在_info
局部文件中,还是其他地方?当局部文件被你的第一个示例调用时,错误是否会引发,还是你从其他地方调用它?我问这个问题是因为你提到了冗余的局部文件,但你没有说过你是否从多个地方调用该局部文件。 - Arsen7render 'info',:locals => { ... }
。如果你是显式调用局部视图,render :partial => 'info',:locals => { ... }
,那么我看不出任何原因导致它不工作。如@Arsen7所建议的那样,了解你的模板嵌套局部视图的方式将会很有帮助。 - neezer