Rails 3,将局部变量传递给partial [英] Rails 3, passing local variable to partial
本文介绍了Rails 3,将局部变量传递给partial的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
Possible Duplicate:
Rails: confused about syntax for passing locals to partials
我想将局部变量(在模型中没有相关字段)传递给局部变量.
I want to pass local variable(which doesn't have relevant field in model) to partial.
# infos/index.html.erb
<%= render :partial => 'info', :locals => {:info => first, :img_style => "original"} %>
:img_style将是图像的html样式.
:img_style will be html style for image.
# 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
但是它不起作用,它返回错误:
But it does not work, it returns error:
# GET /infos/
undefined local variable or method `img_style' for #<#<Class:0xc471f34>:0xc470cc4>
可以做到而不必制作多余的局部片段吗?
It can be done without making redundant partials?
对不起,我的英语. :P
Sorry for my English. :P
好的模型信息没有:img_style字段
Well model Info don't have :img_style field
# 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
甚至很简单
<%= 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'
观看次数
# 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中使用这种语法:
I actually just use this syntax in Rails 3:
render "a_partial", :a_local_variable => whatever, :another_variable => another
这篇关于Rails 3,将局部变量传递给partial的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文