简体   繁体   English

将重复视图HTML重构到Ruby的每个循环中

[英]Refactor repetitive view HTML into each loop for Ruby

I have the following HTML code 我有以下HTML代码

<div class="col-xs-1"> 
    <img src="/assets/X.jpg" class="img-responsive" alt="X">
    <h6>X</h6>
</div>

<div class="col-xs-1">
    <img src="/assets/Y.jpg" class="img-responsive" alt="Y">
    <h6>Y</h6>
</div>

<div class="col-xs-1"> 
    <img src="/assets/Z.jpg" class="img-responsive" alt="Z">
    <h6>Z</h6>
</div>
...

As you can see there's a ton of redundancy (especially since it's actually repeating 10+ times not just the 3 I have here). 如您所见,这里有大量的冗余(特别是因为它实际上重复10次以上,而不仅仅是我这里的3次)。 I'm trying to think through how to make something like this into a DRY each loop, but am having a bit of difficulty. 我试图通过每个循环将这样的东西制作成DRY的方式进行思考,但是有点困难。

I initially thought to just declare in the controller for this view: 我最初以为只是在控制器中为此视图声明:

@images = ["X", "Y", "Z"]

And then in the view do 然后在视图中做

<% @images.each do |image| %>
<div class="col-xs-1">
    <img src="/assets/#{image}.jpg" class="img-responsive" alt="#{image}">
    <h6>"#{image}"</h6>
</div>
<% end %>

But this syntax must not be right since all of the images show up broken. 但是此语法不能正确,因为所有图像都显示为残破的。 Any thoughts on what I'm doing wrong? 对我在做什么错有任何想法吗?

Also, if this turned out to be a not very efficient way of refactoring, I'm very open to suggestions! 另外,如果事实证明这不是一种非常有效的重构方法,那么我也很乐意提出建议!

You're expecting the #{image} to interpolate, but that code in image src , alt attributes are just text and not ruby. 您希望插入#{image} ,但是image src中的代码alt属性只是文本,而不是ruby。 Same applies for text in h6 tag. 同样适用于h6标签中的文本。

You need to use erb scriplets <%=...%> around them to output their values. 您需要在它们周围使用erb scriplets <%=...%>来输出其值。

Update your view code with the following: 使用以下更新视图代码:

<% @images.each do |image| %>
<div class="col-xs-1">
    <img src="<%= "/assets/#{image}.jpg" %>" class="img-responsive" alt="<%= "#{image}" %>">
    <h6><%= "#{image}" %></h6>
</div>
<% end %>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM