簡體   English   中英

使用Rails幫助器嵌套HTML元素

[英]Nested HTML elements with Rails helper

我正在使用Rails html幫助器來創建帶有labelselectoptgroups的簡單html結構(這是唯一稍微復雜的部分)。

然后,我創建了一個名為resources_optgroup的助手。 我想要這樣的輸出:

<div>
    <label>Something</label>
    <select name="something">
        <optgroup label="something">
            <option value="1">something</option>
            <option value="2">something</option>
            <option value="3">something</option>
        </optgroup>
        <optgroup label="something">
            <option value="1">something</option>
            <option value="2">something</option>
            <option value="3">something</option>
        </optgroup>
    </select>
</div>

這是我的Rails代碼。 標簽和選擇標簽不能同時使用。 這是什么?

def collection_link(item,site)
      content_tag :div, class: '' do
        label_tag item['title']

        content_tag(:select) do
            concat resources_optgroup site, Page
            concat resources_optgroup site, Category
            concat resources_optgroup site, Post
            concat resources_optgroup site, Product
            concat resources_optgroup site, Service
        end
    end
  end

這些方法返回字符串,而您的方法返回最后執行的操作。 如果需要全部,則需要連接字符串。 這可能會導致一堆html_safe調用以及其他丑陋情況。 更好的解決方案是將HTML生成移至局部視圖,並從您的助手中進行渲染。 您可以將任何計算或變量信息作為本地傳遞。


通過請求-如果您確實想在幫助程序中完成此操作,而無需使用視圖代碼(盡管它是視圖代碼),則可以執行以下操作:

def collection_link(item,site)
  content_tag :div, class: '' do
    label_tag(item['title']) +

    content_tag(:select) do
        resources_optgroup(site, Page) +
        resources_optgroup(site, Category) +
        resources_optgroup(site, Post) +
        resources_optgroup(site, Product) +
        resources_optgroup(site, Service)
    end
  end
end

這幾乎肯定會造成html轉義問題。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM