Reputation: 445
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.
Upvotes: 3
Views: 1304
Reputation: 6337
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.
Upvotes: 5
Reputation: 13972
What you want to do is possible. There's some documentation from the HAML page, and here's my guess how you might use it in your situtation:
def my_thing
haml_engine = Haml::Engine.new(".div_class
this is my attempt at HAML")
haml_engine.render
end
Having said that, I suggest you don't do something like that, and instead use Rails (built-in) helpers or the Presenter pattern (emerging in the Rails community via my own delegate_presenter or Draper to create complex HTML widgets/elements
Upvotes: 1