简体   繁体   中英

Nested HTML elements with Rails helper

I am using the Rails html helper to create a simple html structure with a label , a select and optgroups (this is the only slightly complicated part).

I then created a helper called resources_optgroup . I want an output like this:

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

And this is my Rails code. I can't make both,the label and the select tags to work together. What is this?

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

Those methods return strings, and your method returns the last thing that is performed. If you want it all, you will need to concatenate your strings. This will likely lead to a mess of html_safe calls, and other ugliness. A better solution would be to move the HTML generation to a view partial, and render it from your helper. You can pass any calculated or variable information in as locals.


By request - if you really want to make this in a helper, without using view code (despite the fact that it is view code), you can do something like:

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

This will almost certainly create html escaping issues....

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