Generating dynamic ERB using ERB generator

时间:2016-02-12 21:39:43

标签: html ruby ruby-on-rails-3 templates generator

For most of my projects, I use the same ole view for my index pages. The html is usually along the lines of this.

Desired html outcome:

GROUP BY

Fairly straight forward. The issue I'm having is that the generator I'm creating uses ERB tags to create the html code. I need to use ERB tags to create ERB tags.

<h1>Chairs</h1>

<table class="table table-striped">
  <thead>
    <tr>
      <th>Color</th>
      <th>Size</th>
      <th>Fabric</th>
      <th>Description</th>
    </tr>
  </thead>

  <tbody>
    <% @chairs.each do |chair| %>
      <tr>
        <td><%= chair.color %></td>
        <td><%= chair.size %></td>
        <td><%= chair.fabric %></td>
        <td><%= chair.description %></td>
      </tr>
    <% end %>
  </tbody>
</table>`

This is what i have, but it's obviously wrong. <h1><%= plural_table_name %></h1> <table class="table table-striped"> <thead> <tr> <%- if !options[:fields].empty? -%> <%- options[:fields].each do |field| -%> <th><%= field.capitalize %></th> <%- end -%> <%- end -%> </tr> </thead> <tbody> **** <%- @plural_table_name.each do | singular_table_name | -%> <%- if !options[:fields].empty? -%> <%- options[:fields].each do |field| -%> <tr> **** <td><%= singular_table_name.field %></td> </tr> <%- end -%> <%- end -%> **** <%- end -%> </tbody> </table> is an array that's working correctly because the options[:fields] block is showing what I need it to. My issue is creating an ERB tag that will return an ERB string rather than running the code that's inside. I believe I isolated the issue and noted the lines with <thead>. I need these lines to show as is, but I need **** and plural_table_name to change dynamically according to the table. I'm not sure what the proper syntax is or if it's even possible. Any help is appreciated.

1 个答案:

答案 0 :(得分:2)

您可以使用双倍百分比<%%来逃避Erb中的<%(即,Erb会读取<%%并将<%写入输出,并且不会对待内容为Ruby)。

您需要执行以下操作:

<%% <%= a_plural_variable %>.each do | <%= a_singular_variable %> | %> 

获取您想要的输出。该行将被评估为(假设变量的适当值):

<% chairs.each do | chair | %>

请注意,最后一个%>被解释为纯文本,不需要转义。