Nesting content tags in rails

2019-08-07 13:35发布

问题:

Hey. I've got some code from Agile Web Development that wraps some HTML around a method call as so:

  # 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

I would like to nest a span tag within the label content_tag, so that the final output would be along the lines of:

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

I am wondering how I go about including the span's content (say a variable such as 'warning')

I have tried all sorts, to no avail. The methods call ok (such as f.text_field :name will produce

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

Have tried this:

  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

But no luck. Can anyone steer me in the right direction? Thanks, A

回答1:

You need to call @template.content_tag. The code you have there is just calling self.content_tag, which obviously doesn't do anything.



回答2:

Just wanted to post the final solution, more for pride than anything else. Noob... :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