视图中.html.erb中的if else语句 [英] If else statements in .html.erb in views
问题描述
在铁轨中,我经常遇到这样的情况,在视图内部我会做类似的事情
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屋!