[英]Rails views: how to prevent empty HTML tags from being output?
通常,在HTML中,我不得不輸出例如這樣的鏈接列表:
/ Note: SLIM template!
ul
- if can? :edit, User
li Create
- if can? :destroy, User
li Destroy
當兩個都can?
時,這會導致輸出空的ul
標簽can?
s返回false。 防止這種情況的常見模式是什么? 我唯一能想到的是以下內容:
- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
ul
- if edit
li Create
- if destroy
li Destroy
但這在我看來很笨拙。 有更好的主意嗎?
首先,我很驚訝看到人們最終更喜歡苗條而不是haml。 我真的很喜歡erb和haml的苗條身材。
其次,我認為這段代碼:
- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
ul
- if edit
li Create
- if destroy
li Destroy
如果edit
或destroy
為false,則不會輸出ul
。
在這種情況下,我更喜歡使用輔助方法(因為您將邏輯移到此處並保持視圖整潔):
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
首先構建允許的動作列表,然后進行輸出。
我不確定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
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.