Sixty4Bit
Sixty4Bit

Reputation: 13402

What is the best way to return multiple tags from a Rails Helper?

I want to create a hidden field and create a link in one helper and then output both to my erb.

<%= my_cool_helper "something", form %>

Should out put the results of

link_to "something", a_path
form.hidden_field "something".tableize, :value => "something"

What would the definition of the helper look like? The details of what link_to and the form.hidden_field don't really matter. What matters is, how do I return the output from two different calls.

Upvotes: 29

Views: 8325

Answers (6)

Clay Shentrup
Clay Shentrup

Reputation: 11

This worked for me.

def format_paragraphs(text)
  text.split(/\r?\n/).sum do |paragraph|
    tag.p(paragraph)
  end
end

Upvotes: 0

estani
estani

Reputation: 26457

def output_siblings
  div1 = tag.div 'some content'
  div2 = tag.div 'other content'

  div1 + div2
end

just simplifying some other answers in here.

Upvotes: 1

Joshua Pinter
Joshua Pinter

Reputation: 47471

Using safe_join.

I typically prefer just concatenating with +, as shown in Orion Edwards's Answer, but here's another option I recently discovered.

safe_join( [
  link_to( "something", something_path ),
  form.hidden_field( "something".tableize, value: "something" )
] )

It has the advantage of explicitly listing all of the elements and the joining of those elements.

I find that with long elements, the + symbol can get lost at the end of the line. Additionally, if you're concatenating more than a few elements, I find listing them in an Array like this to be more obvious to the next reader.

Upvotes: 5

Orion Edwards
Orion Edwards

Reputation: 123622

There are several ways to do this.

Remember that the existing rails helpers like link_to, etc, just output strings. You can concatenate the strings together and return that (which is what I do most of the time, if things are simple).

EG:

link_to( "something", something_path ) +  #NOTE THE PLUS FOR STRING CONCAT
  form.hidden_field('something'.tableize, :value=>'something')

If you're doing things which are more complicated, you could just put that code in a partial, and have your helper call render :partial.

If you're doing more complicated stuff than even that, then you may want to look at errtheblog's block_to_partial helper, which is pretty cool

Upvotes: 26

Jay_Pandya
Jay_Pandya

Reputation: 147

If you want to buffer other output which apart from string then you can use concat instead of +. see this - http://thepugautomatic.com/2013/06/helpers/

Upvotes: 2

Sixty4Bit
Sixty4Bit

Reputation: 13402

So far the best I have come up with is:

def my_cool_helper(name, form)
  out = capture { link_to name, a_path }
  out << capture { form.hidden_field name.tableize, value => 'something' }
end

Is there a better way?

Upvotes: 11

Related Questions