视图中 .html.erb 中的 if else 语句 [英] If else statements in .html.erb in views
问题描述
在 Rails 中,我经常遇到这样的情况,在视图中我会做类似的事情
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 就是这样,因为它的目的是将 Ruby 注入到其他纯文本模板中的最小方式,而不是必须精简或优雅的东西.
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.
好消息是语法高亮编辑器通常会使您的 <% ... %>
ERB 块在视觉上与您的 HTML 不同,从而可以显着提高可读性.
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.
这也是为什么创建了诸如 HAML 之类的其他表示形式,而这种语法却没有那么混乱:
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
这篇关于视图中 .html.erb 中的 if else 语句的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!