leonel
leonel

Reputation: 10224

Rails: how to render HTML inside a link_to block?

I'm using a nested form following rbates approach: http://railscasts.com/episodes/196-nested-model-form-revised

I'm also using Twitter Bootstrap.

I'm trying to add an Add Child button with an icon. So I modify the link_to_add_fields and rename it icon_to_add_fields. This is what I have...

def icon_to_add_fields(name, f, association, icon_class = '', button_color = '')
  new_object = f.object.send(association).klass.new
  id = new_object.object_id
  fields = f.fields_for(association, new_object, child_index: id) do |builder|
    render(association.to_s.singularize + "_fields", f: builder)
  end
  link_to("#", class: "add_fields btn #{button_color}", data: {id: id, fields: fields.gsub("\n", "")}) do
    "<i class='icon-plus-sign icon-white'></i> #{name}"
  end
end

The problem is, instead of rendering <i class="icon-plus-sign icon-white"></i> Add Child as HTML, my button reads <i class="icon-plus-sign icon-white"></i> Add Child on top of it.

So, to "fix" that, I add simple_format like this...

link_to("#", class: "add_fields btn #{button_color}", data: {id: id, fields: fields.gsub("\n", "")}) do
  simple_format "<i class='icon-plus-sign icon-white'></i> #{name}"
end

Now, the HTML inside the link renders well, BUUUT, there are p tags inside, which I do not want.

I'm supposed to end up with something similar to this: <a class="btn btn-primary" href="#"><i class="icon-plus-sign icon-white"></i> Add Child</a>

How can I correct this function to render HTML correctly, but don't output p tags?

Upvotes: 0

Views: 580

Answers (1)

MurifoX
MurifoX

Reputation: 15089

Well simple_format always wrap the results with <p> tags. But as stated on an answer to this question, Rails 3. simple_format do not wrap result in paragraph tags, the method is only 9 lines long and can easily be overwritten to not wrap the contents with <p> tags by removing some of the lines.
So i believe you can make a another_simple_format helper and use it on your icon_to_add_fields method and you would be ok.

Upvotes: 1

Related Questions