In rails, I often run into the situation where inside the views I'll do something like
<% if @some_condition_previusly_established_in_a_controller %> <div class="one">123</div> <% else %> <div class="two">something else</div> <% end %>
It looks a bit cluttery. Is this an acceptable way of working with views or not?
ERB is a templating engine. A templating engine allows you to mix HTML & Ruby so you can generate web pages using data from your database. ERB is Rails default engine for rendering views. Note: Rails uses an implementation called erubi instead of the ERB class from the Ruby standard library.
ERB is a templating language based on Ruby. Puppet can evaluate ERB templates with the template and inline_template functions. This page covers how to write ERB templates. See Templates for information about what templates are and how to evaluate them.
ERB files contain source code written in a programming language of the same name. The ERB language is essentially a Ruby templating language. ERB files are saved in a plain text format which allows them to be opened in any text editing program. Thus, the file can contain any type of text alongside the ERB source code.
Unless you can think of a way to re-write this as a helper method, you're basically stuck with it looking kind of ugly. That's just how ERB is, as it was intended to be a minimal way of injecting Ruby into an otherwise plain-text template, not as something necessarily streamlined or elegant.
The good news is a syntax-highlighting editor will usually make your <% ... %>
ERB blocks look visually different from your HTML so that can dramatically improve readability.
It's also why other representations like HAML have been created where that syntax is a lot less cluttered:
- if some_condition_previusly_established_in_a_controller .one 123 - else .two something else
For one or two such conditional logic in your views, I guess its fine but when your code gets bigger and you have multiple if..else..end
and looks "cluttery", I think you should look at implementing "Presenter Pattern" which greatly cleans up your views by separating your logic to Presenters.
Here is a great tutorial I followed from Ryan Bates in his Rails Casts series on "Presenter Patterns from scratch". http://railscasts.com/episodes/287-presenters-from-scratch.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With