【问题标题】:Rails label_tag do on helper only renders part of the contentRails label_tag 在 helper 上只渲染部分内容
【发布时间】:2017-04-05 06:09:23
【问题描述】:

在我们的应用程序中,我们显示如下输入:

<%= f.label :date, class: 'field' do %>
  <span>Date</span>
  <%= f.text_field :date %>
<% end %>

这经常重复,所以我决定把它放在这样的助手中:

def text_field_for(attribute, title, form, value = nil)
  form.label attribute, class: 'field' do
    content_tag(:span, title)
    form.text_field attribute, value: value
  end
end

但是,这将呈现为 html,如下所示:

<label class="field" for="my_object_date">
  <input type="text" name="my_object[date]" id="my_object_date" />
</label>

为什么它不渲染 span 标签?当我注释掉 text_field 时,它会正确呈现跨度。不知何故,它无法同时渲染它们。

【问题讨论】:

    标签: ruby-on-rails


    【解决方案1】:

    在您的方法中的两行之前添加concat,如下所示:

    def text_field_for(attribute, title, form, value = nil)
      form.label attribute, class: 'field' do
        concat( content_tag(:span, title) )
        concat( form.text_field attribute, value: value )
      end
    end
    

    如果你使用 concat 它将加入你标签块中生成的每个 HTML 块。

    没有它,我只会将最后一行作为内容。 (比如return form.text_field attribute, value: value

    【讨论】:

      【解决方案2】:

      只有最后一条语句从块中返回。您可以使用以下方法将两者结合起来:

      form.label attribute, class: 'field' do
        content_tag(:span, title) + form.text_field(attribute, value: 'bar')
      end
      

      form.label attribute, class: 'field' do
        content_tag(:span, title).concat(form.text_field(attribute, value: 'bar'))
      end
      

      【讨论】:

        【解决方案3】:

        当您制作自己的助手时,您需要使用concat 来向块中添加额外的内容。

        这样的事情应该可以工作:

        def text_field_for(attribute, title, form, value = nil)
          form.label attribute, class: 'field' do
            concat(content_tag(:span, title))
            concat(form.text_field attribute, value: value)
          end
        end
        

        Concat 会将内容添加到输出缓冲区,类似于 &lt;%= content %&gt; 在模板文件中的操作。

        如果你以后想做这样的事情,但你没有块,你需要使用capture,以便内容被捕获并呈现到页面。

        def another_helper
          capture do
            concat link_to("Star wars", star_wars_path)
            concat link_to("Star trek", star_trek_path)
          end
        end
        

        【讨论】:

          猜你喜欢
          • 2013-06-18
          • 2016-12-10
          • 1970-01-01
          • 2015-04-15
          • 2011-10-17
          • 2017-01-31
          • 1970-01-01
          • 2015-11-28
          • 2023-03-13
          相关资源
          最近更新 更多