对导航链接使用Rails的`link_to_unless_current`。

67 阅读1分钟

我们都熟悉经典的Railslink_to 帮助器。但你知道有一个link_to_unless_current 的变体吗?

它的工作原理与链接link_to 相同,只是如果浏览器的当前URL与链接目标相同,它就不会创建链接。

使用方法

只需用link_to_unless_current 替换link_to 。如果你还没有进入该页面,将呈现一个正常的<a> 标签。如果你已经在这个页面上,只有文本会被呈现出来。

<nav class="flex flex-col space-y-1">
  <%= link_to_unless_current "Dashboard", dashboard_path %>
  <%= link_to_unless_current "Team", teams_path %>
  <%= link_to_unless_current "Projects", projects_path %>
  ...
</nav>

当你在/dashboard ,这个模板将输出。

<nav class="flex flex-col space-y-1">
  Dashboard
  <a href="/teams">Teams</a>
  <a href="/projects">Projects</a>
  ...
</nav>

你也可以传入一个块来渲染(而不是链接名称)。这对于制作共享视图很有用。例如,你可以为一个Post 做一个带有动作的局部。

<%= link_to_unless_current "+ Comment", new_comment_path do
  link_to "Back", posts_path
end %>

其他变体

正如你所期望的,如果你想指定你自己的条件逻辑来渲染一个链接或不渲染,还有其他的变体,如link_to_iflink_to_unless

你可能想显示所有Post,但如果你是以管理员身份登录的,标题应该是指向编辑页面的链接。

<% @posts.each do |post| %>
  <%= link_to_if @user.admin?, post.title, manage_post_path(post) %>
<% end %>

其他资源

Rails API 文档。UrlHelper#link_to_unless_current

Rails API 文档。UrlHelper#link_to_if

Rails API Docs:UrlHelper#link_to_unless