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