Si vous cherchez mon site professionnel, merci de cliquer ici.
How to get a clean html code when using the rails erb template system
That’s may be a minor issue, but I find it quite annoying to have the html code messed up by the few logic in the erb templates.
Consider the following erb code :
<ul id="user-bar">
<% if logged_in? %>
<li><%= link_to 'my page', user_url( current_user ) -%></li>
<li><%= link_to 'logout', logout_url -%></li>
<% else %>
<li><%= link_to 'signup', signup_url -%></li>
<li><%= link_to 'login', login_url -%></li>
<% end %>
</ul>
That’s quite readable and makes me a happy dev. But what does the html code look like, after rails processed that?
<ul id=“user-bar”> <li><a href=“http://agora_producteurs/users/1″>my page</a></li> <li><a href=“http://agora_producteurs/logout”>logout</a></li> </ul>
Huh? What’s about those blank lines? Well, let’s put some more <% -%> instead of the <% %> of the conditional.
<ul id=“user-bar”> <li><a href=“http://agora_producteurs/users/1″>my page</a></li> <li><a href=“http://agora_producteurs/logout”>logout</a></li> </ul>
Even worst. This comes from the whitespaces before the condition’s elements. One work around is to write a template like this :
<ul id="user-bar">
<% if logged_in? -%>
<li><%= link_to 'my page', user_url( current_user ) -%></li>
<li><%= link_to 'logout', logout_url -%></li>
<% else -%>
<li><%= link_to 'signup', signup_url -%></li>
<li><%= link_to 'login', login_url -%></li>
<% end -%>
</ul>
And we get the html we want, but now, it’s the erb template that is messed up. I want pretty html, but I for sure don’t want ugly erb code.
The “in the middle” workaround
So here’s what I do : I use the <% -%> form for the logic, I open the tag at the start of the line, and I indent the ruby code.
<ul id="user-bar">
<% if logged_in? -%>
<li><%= link_to 'my page', user_url( current_user ) -%></li>
<li><%= link_to 'logout', logout_url -%></li>
<% else -%>
<li><%= link_to 'signup', signup_url -%></li>
<li><%= link_to 'login', login_url -%></li>
<% end -%>
</ul>
This products this html code :
<ul id=“user-bar”> <li><a href=“http://agora_producteurs/users/1″>my page</a></li> <li><a href=“http://agora_producteurs/logout”>logout</a></li> </ul>
That’s still not perfect, the indentation is four whitespaces whereas it’s two elsewhere, and there is still a bit of junk in the erb file, but that’s a compromise. With my darkblue vim colorscheme, it’s near than invisible, and only the keywords pop up :






Write a Comment