Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/ruby-on-rails/65.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Ruby on rails Rails视图:如何防止空HTML标记被输出?_Ruby On Rails_View - Fatal编程技术网

Ruby on rails Rails视图:如何防止空HTML标记被输出?

Ruby on rails Rails视图:如何防止空HTML标记被输出?,ruby-on-rails,view,Ruby On Rails,View,通常情况下,在HTML中,我必须输出如以下链接列表: / Note: SLIM template! ul - if can? :edit, User li Create - if can? :destroy, User li Destroy 这导致当两个都可以返回false时,输出空的ul标记。预防这种情况的常见模式是什么?我唯一能想到的是: - if edit = can?(:edit, User) && destroy = can?(:destroy

通常情况下,在HTML中,我必须输出如以下链接列表:

/ Note: SLIM template!
ul
  - if can? :edit, User
    li Create
  - if can? :destroy, User
    li Destroy
这导致当两个
都可以返回false时,输出空的
ul
标记。预防这种情况的常见模式是什么?我唯一能想到的是:

- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
  ul
    - if edit
      li Create
    - if destroy
      li Destroy

但这在我看来很笨拙。有更好的主意吗?

先建立允许操作的列表,然后进行输出

我对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 
-allowed=[]
-如果可以的话:编辑,用户

首先,我很惊讶地看到人们最终喜欢苗条而不是哈姆。我真的很喜欢slim而不是erb和haml

第二,我认为这个代码:

- if edit = can?(:edit, User) && destroy = can?(:destroy, User)
  ul
    - if edit
      li Create
    - if destroy
      li Destroy
如果
edit
destroy
为false,则不会输出
ul

在这种情况下,我更喜欢使用helper方法(因为您将逻辑移动到那里并保持视图干净):


我认为应该完全避免观点中的所有逻辑。好的,你可以把它移入控制器,但很快就会变得一团糟。PS:你应该看看斯利姆。我使用HAML多年,自从知道SLIM之后,我就完全不使用它了。;-)这是一个有趣的方法。但是我想有一些通用的解决方案,它不会强迫我为每个特定的情况创建一个助手。我在考虑一些助手,比如
content\u tag
,它可以自动去除空标签…?附:我喜欢斯利姆已经两年了,但是我的同事们都很无知,我无法说服他们去看看斯利姆。现在我辞职了,只和斯利姆一起工作。
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