如何在HAML中执行if/else,而无需重复缩进代码 [英] How to do an if/else in HAML without repeating indented code

查看:66
本文介绍了如何在HAML中执行if/else,而无需重复缩进代码的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据用户是否登录,我想打印另一种%body-tag.

Depending on if a user is signed in or not, I'd like to print a different kind of %body-tag.

这是我目前的操作方式:

This is how I currently do it:

- if defined? @user
  %body(data-account="#{@user.account}")
    %h1 Welcome
    -# all my content
- else
  %body
    %h1 Welcome
    -# all my content

如您所见,其中有很多重复的代码.我该如何消除呢?我已经尝试过以下方法:

As you can see there's a lot of duplicated code in there. How can I eliminate this? I already tried the following:

- if defined? @user
  %body(data-account="#{@user.account}")
- else
  %body
  %h1 Welcome
  -# all my content

不幸的是,这是行不通的,因为HAML会将其解释为%h1,而其内容是else语句的一部分,而它们当然不是.

Unfortunately, this doesn't work since HAML interprets it as if the %h1 and the content is part of the else-statement, which of course they aren't.

关于如何解决此问题的任何想法?我一直都在遇到这个问题,所以我无法想象没有一个简单的解决方案.

Any ideas on how to solve this? I run in this problem all the time, so I can't imagine there isn't a simple solution for it.

推荐答案

!!!
 - @user = "jed" #=> stubbing out an instance
%html
  %head
    - string = defined?(@user) ? "#{@user}" : nil #=> for demo only, wrap this in a helper method
    %title{'data-account' => string}
  %body
    =yield

这篇关于如何在HAML中执行if/else,而无需重复缩进代码的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆