简体   繁体   English

Rails视图:有条件地显示文本和链接; 有没有比这更简单的方法?

[英]Rails view: display text and a link, conditionally ; Is there a simpler way than this?

In a Rails (erb) view, I want to conditionaly display some text and a link. 在Rails(erb)视图中,我想有条件地显示一些文本和链接。

Is there anything simpler than that: 还有什么比这更简单的了:

<% if some_condition %>
        Go to  
<%=     link_to("Home", root_url) %>
<%  else %>
        See all
<%=     link_to("objects", my_objects_path) %>
<%  end %>

I am a bit annoyed by the number of <% and <%= tags. <%<%=标签的数量让我有点恼火。

As a helper (depending on actual usage, it could be an application-wide helper, a model helper, etc): 作为助手(取决于实际用法,它可以是应用程序范围的助手,模型助手等):

def home_or_objects c
  if c
    link_to "Go to home", root_url
  else
    link_to "See all objects", my_objects_path
  end
end

(I wouldn't linkinate only a single word--smaller target, and IMO less communicative. YMMV.) (我不会只链接一个单词-目标更小,IMO的交流也更少。YMMV。)

Then in the view: 然后在视图中:

<%= home_or_objects some_condition %>

As a partial it's a matter of rendering the partial, perhaps passing the condition in as a local, or if it's an instance variable, it can be referenced directly without needing to be passed. 作为局部变量,只需渲染局部变量,也许将条件作为局部变量传入,或者如果它是实例变量,则可以直接引用而无需传递。

<%= render :partial => 'home_or_objects', :locals => { :c => some_condition } %>

(There are a few ways a partial could be handled. IMO a helper is more appropriate.) (有几种方法可以处理部分内容。IMO助手更合适。)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM