“- if ... - else”命令与哈巴狗中的 "if ... else" 命令相同吗?

Are the "- if ... - else" command same with "if ... else" command in pug?

pug 中有两种定义 if...else 逻辑的类型。

选项 1(-

- var a = 5
- var content = {"b":"<style></style>"}
- if (content.b)
  div !{a} !{content.b}
- else
  div test

选项 2(没有 -

- var a = 5
- var content = {"b":"<style></style>"}
if (content.b)
  div !{a} !{content.b}
else
  div test

他们都可以提供与我想要的相同的正确逻辑。我只想知道它们是否相同?为什么有时我必须添加 - 而有时我不需要?

他们几乎一样。

  • 如果您省略连字符,条件周围的括号是可选的。
  • 如果使用连字符,则需要括号。

否则没有实际区别。

如果您在 if 中使用连字符,则还必须在同级 else ifelse 中使用连字符。反之亦然。 (混合使用连字符和非连字符似乎在某些情况下可行,但这样的代码会造成混淆,所以不要这样做。)

Pug v1(也称为 Jade)需要前导连字符。来自 Conditionals in Pug docs:

Pug’s first-class conditional syntax allows for optional parentheses.

If you’re coming from Pug v1, you may now omit the leading -. Otherwise, it’s identical (just regular JavaScript)

有效:

// No hyphens -> no parentheses required
if foo
  p text
else if bar
  p text
else
  p text

// No hyphens -> parentheses are allowed
if (foo)
  p text
else if (bar)
  p text
else
  p text

// Hyphens -> parentheses are required
- if (foo)
  p text
- else if (bar)
  p text
- else
  p text

无效:

// Hyphens -> should use parentheses
- if foo
  p text
- else if bar
  p text
- else
  p text

// Mixing hyphens and no-hyphens -> invalid or at least confusing
if (foo)
  p text
- else if (bar)
  p text
else
  p text