首页 > 解决方案 > Pug 中的条件语句

问题描述

我有以下用例,在我的项目中,我有两个不同的页脚。感谢@sean 的建议,我尝试了一个案例陈述。这是我的模板:

//- layout.pug
include head

body
    block nav
        include nav

    block content  

    block footer

        case chooseFooter
            when 1
                include footer1
            when 2 
                include footer2        

    block scripts
        script(src='js/index.js')

这是第一个页脚:

li
  .footer_contact1

li
  .footer_contact1

 这是第二个页脚:

ul.boxes
      li
      .footer_contact2

    li
      .footer_contact2

这是调用模板的索引页面:

extend includes/layout

append content
    .promo

    ul.boxes
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper
        li
          .boxes__text-wrapper

prepend footer
        - let chooseFooter = 1

如果我选择footer1,问题就一致了,我得到以下输出:

<div class="promo">
    <p>some text</p>
  </div>
  <ul class="boxes">
    <li>
      <div class="boxes__text-wrapper"></div>
    </li>
    <li>
      <div class="boxes__text-wrapper"></div>
    </li>
    <li>
      <div class="boxes__text-wrapper"></div>
    </li>
    <li>
      <div class="boxes__text-wrapper"></div>
    </li>
</ul>
<li>
      <div class=".footer_contact1"></div>
 </li>
<li>
      <div class=".footer_contact1"></div>
 </li>

<script src="js/index.js"></script>

所以第一个页脚中的 li:s 在 ul 之外,它们应该在结束 ul 之内。

如果我不使用案例代码而只是做一个正常的包含并将其插入到索引文件中的最后一个 li 项之后并使用以下内容:

li
   .boxes__text-wrapper

include includes/footer

然后在结束 ul 标记之前嵌入 footer1 li 项目。但是我自然不能只使用一个页脚。

我希望这次我更有意义。

谢谢 :)

标签: htmlpug

解决方案


试试这个方法。在模板块中设置一个条件语句或case语句来检查变量的值。

布局.pug

html
  head
    block head

  body
    nav
    block content
    block footer
      footer
        case whichFooter
          when 1
            p Some footer content
          when 2
            p Some other footer content
          default
            p Some other default footer content
    block scripts
      script(src='/my.js')
      script(src='/pets.js')

然后在您的页面中定义该变量,并将添加到模板中的相应块中。

page.pug

extends layout

append head
  title Page A

append content
  p My page content...

prepend footer
  - let whichFooter = 1

这样,您就可以在 pug 需要它来检查条件或 case 语句之前有效地定义变量。

(也不要忘记将它嵌套在nav里面body而不是旁边。)


推荐阅读