2016-02-12 46 views
0

對於我的大部分項目,我使用相同的ole視圖作爲我的索引頁面。 html通常是沿着這條線。使用ERB生成器生成動態ERB

所需的HTML結果:

<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>` 

相當直截了當。我遇到的問題是我創建的生成器使用ERB標籤來創建html代碼。我需要使用ERB標籤來創建ERB標籤。

<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> 

這是我的,但它顯然是錯誤的。 options[:fields]是一個正常工作的數組,因爲<thead>塊顯示我需要它。我的問題是創建一個ERB標籤,它將返回一個ERB字符串,而不是運行裏面的代碼。我相信我隔離了這個問題,並注意到****。我需要這些線顯示,但我需要plural_table_namesingular_table_name根據表動態更改。我不確定什麼是正確的語法,或者甚至可能。任何幫助表示讚賞。

+0

你想分析兩次嗎?例如解析erb並返回erb然後再解析生成html? – engineersmnky

+0

@engineersmnky基本上,是的。我正在運行我的生成器來爲我創建我的html文件。 –

回答

1

您可以使用雙重百分數<%%在Erb中轉義<%(即Erb將讀取<%%並將<%寫入輸出,並且不會將內容視爲Ruby)。

你需要做的事情一樣:

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

得到你想要的輸出。這條線路將進行評估,以(變量假設適當的值):

<% chairs.each do | chair | %> 

注意最後%>被解釋爲純文本,不需要逃跑。