【问题标题】:Nested HTML elements with Rails helper使用 Rails 助手嵌套 HTML 元素
【发布时间】:2015-12-16 04:09:00
【问题描述】:

我正在使用 Rails html 助手创建一个简单的 html 结构,其中包含 labelselectoptgroups(这是唯一稍微复杂的部分)。

然后我创建了一个名为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 ruby-on-rails ruby ruby-on-rails-4


    【解决方案1】:

    这些方法返回字符串,而您的方法返回最后执行的操作。如果你想要这一切,你需要连接你的字符串。这可能会导致 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 转义问题......

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-06-30
    • 2010-12-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多