简体   繁体   English

使用Rails帮助器嵌套HTML元素

[英]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). 我正在使用Rails html帮助器来创建带有labelselectoptgroups的简单html结构(这是唯一稍微复杂的部分)。

I then created a helper called resources_optgroup . 然后,我创建了一个名为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. 这是我的Rails代码。 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. 这可能会导致一堆html_safe调用以及其他丑陋情况。 A better solution would be to move the HTML generation to a view partial, and render it from your helper. 更好的解决方案是将HTML生成移至局部视图,并从您的助手中进行渲染。 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.... 这几乎肯定会造成html转义问题。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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