我经常在HTML中输出例如像这样的链接列表:
/ Note: SLIM template!
ul
- if can? :edit, User
li Create
- if can? :destroy, User
li Destroy
当两个ul
返回false时,这会导致输出空的can?
标记。什么是防止这种情况的常见模式?我唯一能想到的是:
- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
ul
- if edit
li Create
- if destroy
li Destroy
但这对我来说看起来很笨拙。还有更好的主意吗?
答案 0 :(得分:1)
首先,我很惊讶地看到人们最终更喜欢苗条而不是haml。我真的很喜欢erb和haml。
其次,我认为这段代码:
- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
ul
- if edit
li Create
- if destroy
li Destroy
如果ul
或edit
为假,将不会输出destroy
。
在这种情况下,我更喜欢使用辅助方法(因为你在那里移动逻辑并保持视图干净):
module ApplicationHelper
def show_content_for(user)
contents = []
contents << "Create" if can? :edit, user
contents << "Destroy" if can? :destroy, user
content_tag :ul do
contents.collect { |content| concat(content_tag(:li, content)) }
end unless contents.blank?
end
end
在苗条的视野中:
= show_content_for User
答案 1 :(得分:0)
首先构建允许的操作列表,然后执行输出。
我不确定SLIM语法。我使用HAML。
- allowed = []
- if can? :edit, User
allowed << li Create
- if can? :destroy, Use
allowed << li Destroy
- if allowed.count
ul
- allowed.each do |l|
l