Rails Helpers - What is the best approach when building an html string?

I usually write helpers:

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 usually see people using other approaches, for example:

  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 last two in the past and ran into some problems, and then started using the helpers content_tag and tag, even if I sometimes have to use the .html_safe method.

Is there a standard way to create helpers?

+6
source share
4 answers

If html is longer than 1 line, I usually put html in partial and call it using a special helper method

view

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

assistant

 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> 
+5
source

The best approach is to write ruby ​​code in helpers and html only in .html.erb files, even if thay are β€œlines”, so you should use content_tag for helpers, and if you want to use one block:

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

and if your html is big, think about conveying the particle, hope this clarifies your doubts.

+2
source

If you want to create a longer "safe" html, it is recommended:

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

Actually, you can and should use partial ones as helpers. Having raw html tags outside of views is the smell of code that I try to avoid as much as possible.

Related question: Rails view helpers in a helper file

0
source

Source: https://habr.com/ru/post/924802/


All Articles