简体   繁体   中英

Using ERB variables to DRY up html

I want to DRY up my ERB with the below:

<div>
  <section class="item">
    +
    <%= render partial: "layouts/list-item" %>
  </section>
  <section class="item">
    +
    <%= render partial: "layouts/list-item" %>
  </section>
  <section class="item">
    +
    <%= render partial: "layouts/list-item" %>
  </section>
</div>

I want to do something like this to not have to repeat myself but it's throwing an error. Do I have to use a for loop instead?

</div>
  <% item = '      <section class="item">
          +
          <%= render partial: "layouts/list-item" %>
        </section>'
  %>
  <%= item * 3 %>
</div>

You could use :

<div>
  < ["", "+", "+"].each do |item| >
    <section class="item">
      <%= item >
      <%= render partial: "layouts/list-item" %>
    </section>
  < end >
</div>

For anything more complex, you could define instance variables in controller, and use basic logic in views (as the loop in this example) to display the data from those variables.

Data should come from a model via controller, html elements should be in views or helpers.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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