Alexandre Abreu
Alexandre Abreu

Reputation: 1417

Helpers in Rails - What's the best approach when building the html string?

I usually write helpers that way:

  def bloco_vazio (texto = "", btn = "", args={})
      titulo = content_tag :h3, "Vazio!" 
      p = content_tag :p, texto
      content_tag :div, (titulo + tag(:hr) + p + btn ), args
  end

But i commonly see people using other approaches, like:

 def flash_notice
    html = ""
    unless flash.empty?
      flash.each do |f|
        html << "<div class='alert alert-#{f[:type].to_s}'>"
        html << "<a class='close' data-dismiss='alert'>×</a>"
        html << f[:text].to_s
        html << "</div>"
      end
    end
    html
 end

or

def a_helper (some_text ="")
  %{ <h3>some title</h3>
      <p>#{some_text}</p>    
  }%
end

I used these two lasts in the past and ran into some problems then started using the content_tag and tag helpers, even that i still have to use the .html_safe method sometimes.

Is there a standard way to build helpers?

Upvotes: 14

Views: 10471

Answers (4)

hsgubert
hsgubert

Reputation: 2264

If you want to build a longer "safe" html the recommended way is:

html = "".html_safe
html.safe_concat "Testing boldfaced char <b>A</b>"
html

Upvotes: 3

Nolasco
Nolasco

Reputation: 100

The best approach is to write ruby code in the helpers and html only on .html.erb files, even if thay are "strings", so you should use the content_tag for helpers and if you want one block you could use:

<%= content_tag :div, :class => "strong" do -%>
 Hello world!
<% end -%>

and if your html is big consider transfering to a partial, hope it elucidates your doubt.

Upvotes: 4

prusswan
prusswan

Reputation: 7091

Actually, you can and should make use of partials in view helpers as well. Having raw html tags outside of views is a code smell that I try to avoid as much as possible.

Related question: Rails view helpers in helper file

Upvotes: 0

emrahbasman
emrahbasman

Reputation: 2013

If html is longer than 1 line, i usually put the html in a partial and call it with a custom helper method

view

<= display_my_html(@item, {html_class: "active"}) %>

helper

def display_my_html(item, opts={})
  name = item.name.upcase
  html_class = opts.key?(:html_class) ? opts[:html_class] : "normal"

  render "my_html", name: name, html_class: html_class
end

partial

<div class="<%= html_class %>">
  <span class="user">
    <%= name %>
  </span>
</div>

Upvotes: 12

Related Questions