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?
What are helpers in Rails? A helper is a method that is (mostly) used in your Rails views to share reusable code. Rails comes with a set of built-in helper methods. One of these built-in helpers is time_ago_in_words .
Rails comes with a wide variety of standard view helpers. Helpers provide a way of putting commonly used functionality into a method which can be called in the view. Helpers include functionality for rendering URLs, formatting text and numbers, building forms and much more.
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>
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With