views:

484

answers:

4

I have heard that it's best not to actually have any html in your helpers; my question is, Why not? And furthermore, if you were trying to generate an html list or something like that, how can I avoid actual tags?

Thanks!

-fREW

+2  A: 

This isn't a full answer to your question, but you can create html in your tags via the content_tag method. My guess as to why would be cleanliness of code.

Also, content_tag allows you to nest tags in blocks. Check out this blog post on content_tag.

Sixty4Bit
Well, I can do that, but really that's the same thing; it's still very specific view code.
Frew
It has the same result, but is "cleaner". It is a similar argument that happens in the Java Web App world with taglibs vs <% %> expressions. In the end it depends on what you and your team decide as the "right way".
Sixty4Bit
A: 

As mentioned before, helpers are generally thought to be used as business logic, for doing something that drives view code, but is not view code itself. The most conventional place to put things that generate snippets of view code is a partial. Partials can call a helper if needed, but for the sake of keeping things separated, it's best to keep business in the helper and view in the partial.

Also, bear in mind this is all convention, not hard and fast rules. If there's a good reason to break the convention, do what works best.

Misplaced
I don't think I agree that helpers are for business logic. Any kind of helper that is view related is much more about view logic than business logic. I would think the core business logic of any application should be stored at the model layer, with perhaps some at the controller layer
Cameron Booth
+6  A: 

My advice - if it's small pieces of HTML (a couple of tags) don't worry about it. More than that - think about partials (as pulling strings of html together in a helper is a pain that's what the views are good at).

I regularly include HTML in my helpers (either directly or through calls to Rails methods like link_to). My world has not come crashing down around me. In fact I'd to so far as to say my code is very clean, maintainable and understandable because of it.

Only last night I wrote a link_to_user helper to spits out html with normal link to the user along with the user's icon next to it. I could have done it in a partial, but I think link_to_user is a much cleaner way to handle it.

RichH
+1  A: 

I don't see that there's anything wrong with it. The majority of the rails helpers generate HTML code (which is their purpose) - to me this implies that's what you're supposed to do yourself.

There is however the ever-present issue of code readability. If you have a helper which just builds a big string of raw HTML, then it's going to be hard to understand. While it's fine to generate HTML in helpers, you should do it using things like content_tag, and render :partial rather than just return %Q(<a href="#{something}">#{text}>)

Orion Edwards