【问题标题】:Haml: If statement inside attribute declarationHaml:属性声明中的 If 语句
【发布时间】:2015-12-24 02:35:44
【问题描述】:

我正在尝试为样式属性设置条件。根据this answer,这样的事情应该是可能的:

.hello{:style => (true ? 'color: green' : 'color: red;')}

但对我来说,style 属性根本不会被输出。哈姆尔的情况有变化吗?我宁愿不为这种简单的逻辑创建助手。

【问题讨论】:

  • 您的代码应该可以工作(并且在我测试时对我有用)。你说属性根本不会被渲染——如果值被评估为falsenil,就会发生这种情况。
  • @matt:我也只能在控制台中使用
  • 你的真实代码是什么样的? (我假设您并没有真正测试文字 true 的真实性)。
  • @matt:是的,我尝试了与控制台中完全相同的代码。
  • 应该肯定有效。退后一步。您正在编辑正确的文件吗?是否涉及任何缓存?您是否有多个服务器正在运行并且正在浏览器中访问错误的服务器? HTH

标签: ruby-on-rails ruby haml


【解决方案1】:

我会采取简单的路线并添加一行:

- color = true ? 'color: green' : 'color: red;'
.hello{:style => color}

更简单的方法是添加更多类并根据需要从 css/javascript 控制它:

- success_class = true ? 'success' : 'failed'
.hello{:class => success_class}

这会给你<div class='hello success'></div>


编辑:不过,三元组似乎也可以工作

require 'haml'
# => true
str = ".hello{:class => true ? 'green' : 'red' }"
# => ".hello{:class => true ? 'green' : 'red' }"
Haml::Engine.new(str).render

# => "<div class='green hello'></div>\n"
str = ".hello{:style => true ? 'color:green' : 'color:red' }"
# => ".hello{:style => true ? 'color:green' : 'color:red' }"
Haml::Engine.new(str).render
# => "<div class='hello' style='color:green'></div>\n"

【讨论】:

  • 如果这是唯一的方法,我一定会创建一个助手
  • @dan-klasson 我刚刚添加了一些检查。
  • 好吧,这很奇怪,我也可以在控制台中使用它,但在实际视图中却不行
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-03-19
  • 2012-04-21
  • 2018-07-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多