用三元运算符表达条件HAML

用三元运算符表达条件HAML

本文介绍了用三元运算符表达条件HAML的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

试图用一种三元运算符来提出一种更紧凑的方式来在HAML和Ruby中表达该条件:

Trying to come up with a more compact way of expressing this conditional in HAML and Ruby, perhaps with a ternary operator:

- if @page.nil?
  %br (nothing yet)
- else
  %br #{@page.name}

(根据)

您的帮助将不胜感激:)

Your help would be appreciated :)

推荐答案

您拥有的代码使文本成为<br>元素的子元素;那是不可取的.我认为您真正的意思是:

The code you have makes the text a child of the <br> element; that is not desirable. What you really meant, I think, was:

%br
- if @page.nil?
  (nothing yet)
- else
  #{@page.name}

为此,您可以简单地执行以下操作:

For this you can simply do:

%br
#{@page.nil? ? "(nothing yet)" : @page.name}

%br
= @page.nil? ? "(nothing yet)" : @page.name

或者简单地:

<br>#{@page ? @page.name : "(nothing yet)"}

但是,我个人将在控制器中对此进行修复",以使您始终拥有@page,其内容如下:

However, personally I would 'fix' this in the controller so that you always have a @page, with something like:

unless @page
  @page = Page.new( name:"(nothing yet)", … )
end

借助此功能,您可以将新页面/空白页面/空白页面的外观显示为残存,并让您的视图像其他页面一样对待它.您的@page仍然没有@page.id,因此您可以将其用于测试以确定是创建新项目还是编辑现有项目.

With this you can stub out what a new/empty/nothing page looks like and let your view treat it like any other. Your @page still won't have a @page.id, so you can use that for tests to decide if you are creating a new item or editing an existing one.

这是我处理所有可用于创建或编辑项目的表单的方式:通过创建(但不添加到数据库中)具有默认值的项目来提供默认值.

This is how I handle all my forms that may be used to create or edit an item: provide defaults by creating (but not adding to the database) an item with the default values.

在旁边:您正在创建一个<br>,它是几乎从来都不是一个好主意,并且您正在使用Haml创建它,它不应用于内容标记.您可能会退后一步,想想自己在做什么.

Aside: You're creating a <br> which is almost never a good idea, and you're creating it with Haml which should not be used for content markup. You might step back and think about what you're doing.

这篇关于用三元运算符表达条件HAML的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-14 05:16