【问题标题】:Nesting content tags in rails在 Rails 中嵌套内容标签
【发布时间】:2009-01-06 16:05:32
【问题描述】:

嘿。我有一些来自 Agile Web Development 的代码,它们在方法调用周围包装了一些 HTML:

  # from tagged_builder.rb, included as a FormBuilder helper
 def self.create_tagged_field(method_name)
    define_method(method_name) do |label, *args|
      @template.content_tag("p",
        @template.content_tag("label" , 
                              label.to_s.humanize.capitalize, 
                              :for => "#{@object_name}_#{label}") 
                               +
        super)
    end
  end

我想在标签 content_tag 中嵌套一个 span 标签,以便最终输出如下:

<p><label>Name
        <span class="small">Add your name</span>
    </label>
    <input type="text" name="textfield" id="textfield" />

我想知道如何包含跨度的内容(比如一个变量,例如“警告”)

我尝试了各种方法,但无济于事。方法调用 ok (如 f.text_field :name 会产生

<p><label for="object_name">Name</label></p>

试过这个:

  def self.create_tagged_field(method_name)
    define_method(method_name) do |label, warning, *args|
      @template.content_tag("p",
        @template.content_tag("label" , 
                              label.to_s.humanize.capitalize+
                              content_tag("span", warning), 
                              :for => "#{@object_name}_#{label}") 
                               +
        super)
    end
  end

但没有运气。谁能引导我朝着正确的方向前进?谢谢,A

【问题讨论】:

    标签: ruby-on-rails ruby forms


    【解决方案1】:

    您需要致电@template.content_tag。您那里的代码只是调用 self.content_tag,这显然没有任何作用。

    【讨论】:

    • 谢谢。我已经实现了 - 谢谢。但是,我仍然无法将变量传递给警告。我想知道你是否能帮助我理解为什么? (我会贴在下面)
    【解决方案2】:

    只是想发布最终解决方案,更多的是为了骄傲。菜鸟... :0

      def self.create_tagged_field(method_name)
        define_method(method_name) do |label, *args|
          # accepts the warning hash from text_field helper
          if (args.first.instance_of? Hash) && (args.first.keys.include? :warning)
            warning = args.first[:warning]
          end
            @template.content_tag("label" , label.to_s.humanize+(@template.content_tag("span", warning, :class =>'small')), 
                                  :for => "#{@object_name}_#{label}") +                      
             super
        end
      end
    

    【讨论】:

      猜你喜欢
      • 2011-05-18
      • 2016-02-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2010-09-08
      相关资源
      最近更新 更多