How to prevent printing variables in view helper?

147 views Asked by At

I have an array, which is loaded from a database. It is in the following format:

["aaa:bbb", "ccc:ddd"]

And need to build an HTML definition list from the array:

<dl>
  <dt>aa</dt>
    <dd>bb</dd>
  <dt>cc</dt>
    <dd>dd</dd>
</dl>

Looks easy, isn't it?

I wanted to create a helper, which would go through the array, split the items on the :'s, and enclose them in tags:

<%= build_def_list(array) %>

However, I have encountered a problem. Namely, when I call a Rails helper from a view, all of its content goes to the output. That is, when I declare a variable within the body of a function and assign a value to it, the variable instantly goes to the output. Is there a way to suppress the printing of everything inside the body of a function?

UPD

Seriously, how to make this with helper?..

<dl>
    <% deflist.each do |item| %>
          <dt><%= item.split(':').at(0) %>:</dt>
            <dd><%= item.split(':').at(1) %></dd>
    <% end %>
</dl>
1

There are 1 answers

7
vee On

Try this for your helper:

def build_def_list(array) 
  content_tag :dl do 
    array.map { |e| e.split(':') }.collect do |dt, dd| 
      content_tag :dt, dt
      content_tag :dd, dd
    end
  end 
end

Then in your view call <%= build_def_list(array) %>

Addition: (To filter what to print)

Thanks to @Arup who reminded me the additional check:

How it would prevent printing all?

To print only specific items, you can filter your input array first deleting any elements you need to remove then use the resultant array to build the content_tags as:

def build_def_list(array) 
 reject_keys = ['ccc'] 
 array = array.map { |e| e.split(':') }.reject { |e| reject_keys.include? e[0] }

 content_tag :dl do 
    array.collect do |dt, dd| 
      content_tag :dt, dt
      content_tag :dd, dd
    end
  end 
end

This will first split the elements of the array by : and delete all the elements if they are found in reject_keys array. The result is then used to build the content_tags.