2016-09-28 58 views
3

这是我在这里的第一篇文章,它可能听起来很愚蠢。我建立我的第一个rails应用程序。如何在0123应用程序中将<img src= >转换为image_tag

我在index.html.erb

<img src="/assets/rand_front/<%= @random_image%>", style='height:50vw;width:100vw;margin-bottom:20px;' > 

此行中我想用image_tag代替img src

什么是它环绕代码的正确方法是什么?

到目前为止,我已经试过<%= image_tag ("/assets/rand_front/<%= @random_image%>", style='height:50vw;width:100vw;margin-bottom:20px;') %>

<%= image_tag ("/assets/rand_front/<%= @random_image%>"), style='height:50vw;width:100vw;margin-bottom:20px;' %>

和其他许多版本,但没有一个似乎工作,我究竟做错了什么?我该如何正确书写它?

这个<%= @random_image%>位从控制器中的index方法中取得这个变量。

def index 
    @products = Product.all.order(created_at: :desc).group_by(&:category_id) 
    @images = ["1.jpg", "2.jpg", "3.jpg", "4.jpg", "5.jpg", "6.jpg", "7.jpg", "8.jpg", "9.jpg", "10.jpg"] 
    @random_no = rand(10) 
    @random_image = @images[@random_no] 
end 
+0

BTW,您可以用'@random_image =“#{兰特(1..10)}。jpg“'或者 - 如果这些只是占位符 - ”@random_image = @ images.sample' – Stefan

回答

4
<%= image_tag ("rand_front/#{@random_image}", style='height:50vw;width:100vw;margin-bottom:20px;') %> 

image_tag会自动在路径的开头添加assets

检查Image Tag的文档

1

如果我没有记错的话,你在你的资产文件夹rand_front文件夹,所以你应该叫image_tag("#{@random_image}")因为默认情况下image_tag助手应检查资产目录中的所有文件夹中的图像名称

对于您可以考虑使用options哈希这将让你在CSS属性通过与你的期望值键

image_tag("#{@random_image}", height: 20, width: 20)您可以在以前的答案

1

此次检查出的文档的CSS属性是什么Ruby on Rails是明确处理

<%= image_tag("source", {:style => "width:100px;"}) %> 

(意思是红宝石允许您与使用此代码了({}),

对于我来说,首先开始重要的是要知道这是Ruby on Rails实际运行代码的方式。

换句话说是,你可以离开({})形式,因为红宝石会理解你的代码,希望有助于澄清一些...

相关问题