Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Alternatives to ERB

I'm getting more heavily into RoR development. ERB doesn't quite feel right to me. I did this once before with JSP. Embedding Ruby code within my markup doesn't feel like a good plan even if the logic is view specific. Mayhaps my fears are unfounded but it feels dangerous. Plus, there's lots of typing involved.

I've found HAML and I'm giving it some more evaluation. If it is a good alternative, mayhaps you can give some good resources for it.

Beyond HAML, what other alternatives to ERB are there for the Rails View layer?

Are my fears with ERB unjustified?

like image 882
Drew Avatar asked Dec 27 '10 22:12

Drew


2 Answers

Embedded Ruby code within a template is not a problem. It offers Erb and Haml tremendous power as template languages. Indeed, many template languages suffer because the templates have no code (e.g., Django's template language).

The real problem that sometimes occurs is when the developer sticks complex code, or code pulling data, or code updating data, or code making decisions, into the template.

Ruby and Rails offer the developer tremendous power and flexibility. It is the responsibility of the developer to be responsible. Retrieve your data from within the controller. Move complex code into a helper. Etc.

<%= link_to edit_post_path(@post) do %>
  Edit post "<%= @post.title %>"!!!
<% end %>

The above is simple Embedded Ruby, and sits well in a view. The Haml version is:

= link_to edit_post_path(@post) do
  Edit post "#{@post.title}"!!!

So long as you keep the code simple, and any complex code is moved into the controller or a helper, you will be fine.

Note that Haml and Erb templates contain equal amounts of embedded Ruby code, with the exception that Haml discards of all the ends.

like image 189
yfeldblum Avatar answered Sep 24 '22 19:09

yfeldblum


If you don't like Ruby in your views, HAML is not going to help you. Although syntactically more succint, it uses embedded Ruby just as ERB does.

If you'd like to avoid logic in your views altogether, have a look at something like Mustache. It uses a templating style that emphasizes a more strict separation of logic from presentation (logic-free views).

like image 35
Milan Novota Avatar answered Sep 21 '22 19:09

Milan Novota