Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mixing Ruby and HAML

I'd like to use Ruby methods to generate the markup that appears frequently in my pages. In essence, I want to do the equivalent of this (ERB file):

<% def create_button(text) %>
    <div class="button"><%= text %></div>
<% end %>
...
<% 
    create_button("My First Button")
    create_button("My Second Button")
    # etc.
%>

Obviously the idea is that any time I need a button, I use create_button.

The Ruby/HAML solution I'm imagining would look something like this:

def create_button(text)
    %div.button text
end

create_button("My First Button")
create_button("My Second Button")

The output of this would be the same as the first block.

Is there a way to do this? If not, ultimately I'm looking for an elegant way to generate markup with Ruby helper methods. If you have any suggestions for how to do this, I'd like to hear it. I'm new to Rails and don't really like ERB, but maybe I'm missing something. Anyway, I'm open to suggestions.

like image 506
Tbabs Avatar asked Jan 01 '26 04:01

Tbabs


1 Answers

You should never need to define a method within a view file in Rails. That's true whether the language is ERb, Haml, or anything else. Instead, put the method in a helper file, then just call it in your view:

app/helpers/some_helper.rb

module SomeHelper
  def button(text)
    content_tag :div, text, :class => :button
  end
end

app/views/whatever/view.html.haml

= button 'My First Button'
= button 'My Second Button'

If you wind up needing a lot of complex helpers, use partials instead, and/or investigate the Cells gem.

like image 140
Marnen Laibow-Koser Avatar answered Jan 02 '26 23:01

Marnen Laibow-Koser



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!