有没有办法提前退出或“返回"?从 Rails 的角度来看? [英] Is there a way to do an early exit or "return" from a view in Rails?
问题描述
Rails 是否提供任何方式来提前退出或从正在呈现的视图中返回"?
Does Rails offer any way to exit early or "return" from a view that is being rendered?
例如,我有一个结构如下的视图:
For example, I have a view structured as follows:
<h1>Your records summary</h1>
<% if @current_user.has_records? %>
<p>You don't have any records.</p>
<% else %>
... long block of view emission code here ...
<% end %>
在非 erb 代码中,我只需要从 if
条件中return
,并且不需要将那个长块放在 else代码>.它看起来像:
In non-erb code, I'd just return
from that if
condition, and wouldn't need to put that long block inside an else
. It would look like:
<h1>Your records summary</h1>
<% if @current_user.has_records? %>
<p>You don't have any records.</p>
<% return (or something) %>
<% end %>
... long block of view emission code here ...
有没有办法在 erb 中做类似的事情?
Is there a way to do something like that in the erb?
需要明确的是,我不是在要求替代方法,例如已经建议的方法.我不是 Rails 菜鸟.我真的只是想知道 Ruby 是否为我的建议提供了一种机制.
To be clear, I'm not asking for alternate approaches, such as have been suggested. I'm not a Rails noob. I really just want to know whether Ruby provides a mechanism for what I suggested or not.
推荐答案
IIRC 没有用于提前退出模板的内置机制.这符合(我认为)视图层的行为方式,尽管 erb 不是一个模板引擎.
IIRC there's no built-in mechanism for exiting a template early. This is in line with how (I think) a view layer should behave, although erb isn't quite a template engine.
旧的解决方案是将模板包装在 catch
中,然后从模板中抛出一些东西,例如符号.
The old-timey solution was to wrap your template in a catch
and throw something from within the template, like a symbol.
您还可以将 eval 嵌入到 Lamba 中,从而允许 return
工作.
You could also embed the eval inside a lamba, allowing return
to work.
尽管如此.
这篇关于有没有办法提前退出或“返回"?从 Rails 的角度来看?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!