如何将一个类添加到字符串的特定部分
问题描述:
我的应用程序头的用户下拉菜单中有以下行。如何将一个类添加到字符串的特定部分
<%= link_to "profile (#{user.notifications.count})", current_user %>
如果用户有三个通知,这应显示profile (3)
。我想为profile
着色与(3)
不同的颜色。
要做到这一点,给两个不同的部分不同的类是最好的方法吗?如果是这样,我该怎么做呢?
答
可以使用do
块:
<%= link_to current_user do %>
profile (<span class='notifications_count'><%= user.notifications.count %></span>)
<% end %>
这将把一个跨度与HTML类'.notificat <a></a>
标签内的“ions_count”。
答
一个快速的方法来实现这一目标是使用span
,像这样
<%= link_to raw("<span style='color: #000'>profile</span> (#{user.notifications.count})"), current_user %>
,或者如果你不想插入内嵌CSS,像这样
<%= link_to raw("<span class='your_profile_class'>profile</span> (#{user.notifications.count})"), current_user %>
+0
你可以使用'html_safe'或'raw'就像我在我的回答中那样。 – 2013-05-07 19:07:02
+0
辅助方法可以使这更容易阅读。 – tadman 2013-05-07 19:10:47
谢谢。我想我更喜欢这样做,因为我觉得它更容易阅读。 (线路不会太长。) – umezo 2013-05-07 19:23:34