【问题标题】:jade: if statements and nesting玉:if 语句和嵌套
【发布时间】:2013-01-19 14:40:25
【问题描述】:

考虑一下这个伪服务器端代码

if(isFixed) {
  <div class="fixed">
} else {
  <div>
}
    <p>Inner element</p>
  </div>

我尝试在翡翠中做到这一点,但是......

 - if(mode === 'fixed') {
   div#tabbar
 - }
     p ...I cannot get this to be an inner element :(

它总是这样渲染,&lt;/div&gt; 关闭:

<div id="tabbar"></div><p>I want this inside of the div</p>

我弄乱了缩进吗? 谢谢!

【问题讨论】:

    标签: pug


    【解决方案1】:

    您需要将控制流与模板分开。试试这个:

    divClass = null
    
    if isFixed
       divClass = "fixed"
    
    div(class=divClass)
       p inner element
    

    这反过来可能建议将“isFixed”参数分解到要传递的实际 divClass 参数中。但这当然取决于您剩余的代码/模板。


    作为替代方案,尝试使用 mixin:

    mixin content
      p inner element
    
    if (isFixed)
      div(class="test")
        mixin content
    else
      div(class="other")
        mixin content
    

    【讨论】:

    • 当然,在这种特殊情况下 (class=tabClass) 正是我正在做的。但我更一般地询问我的例子中的那种事情是否可能。例如。而不是我的
      假设我的 if 语句中有 5 个不同的标签和 10 个不同的属性。
    • 我不相信可以在以前的 IF 中保留缩进级别。从主观的角度来看,这可能会使事情难以理解和混淆。我已经用 mixin 方法更新了我的答案,这可能是更接近您的情况的变体。
    • 这听起来很合理。 mixin 方法看起来更干净。
    • 你也可以分配类内联div(class=(isFixed?'test':'other'))而不需要mixin
    【解决方案2】:

    我会用三元(或完全写出的条件或方法)来确定类属性。这使您可以将 div 保持在一行并保持缩进,就像对任何其他元素一样:

    div(class="#{ isFixed ? 'fixed' : '' }")
        p Inner Element
    

    【讨论】:

    • 我认为这是最不混乱的方式。
    【解决方案3】:

    Jade 似乎没有内置的解决方案来开始和结束标签,而不是使用“管道”字符来呈现纯文本。

    - if(mode === 'fixed') {
    | <div id="tabbar">
    - }
    | <p>I cannot get this to be an inner element :(</p>
    - if(mode === 'fixed') {
    | </div>
    - }
    

    更简洁的解决方案 -

    div(class=(isFixed) ? 'fixed' : '')
      p inner element
    

    【讨论】:

      猜你喜欢
      相关资源
      最近更新 更多
      热门标签