【问题标题】:pug - Incorrect nesting after compilation - include vs extend哈巴狗 - 编译后不正确的嵌套 - 包含与扩展
【发布时间】:2017-07-24 16:20:44
【问题描述】:

编辑:根据正确答案修改标题,以帮助谷歌搜索


在下面的代码中,在404.pug 页面中包含我的header.pug 后,404.pug 页面中的h2 标记不断成为h1 标记的子级。这是我正在使用的代码:

Header.pug

doctype
html
  head
    meta(charset='utf-8')
    title Express Guestbook
    link(href="to/bootstrap.min.css", rel="stylesheet")

  body.container
    h1 Express Guestbook
      a.btn.btn-primary.pull-right(href="/new-entry") Write in Guestbook

    //- putting this div here so that whatever code 'include'-s this 
    //- header, will be a child of this div
    div


404.pug

include header.pug

  //- This part becomes child of <a> tag, instead of <div>
  h2 404! Page not found

include footer.pug


谁能解释一下

  1. 为什么会这样?而且,
  2. 可能展示一种方法来保持h2 标记作为h1 的同级而不成为a 标记的子级?

现在解决此问题的一种可能方法是使用嵌套 div(一个 div 在另一个 div 中)而不是只有一个 div,如下所示:

body.container
  h1 Express Guestbook
    a.btn.btn-primary.pull-right(href="/new-entry") Write in Guestbook

  //- ugly hack
  div: div

但这感觉不太好..

【问题讨论】:

    标签: html node.js express pug


    【解决方案1】:

    您可能想要使用extends header.pug 而不是include header.puginclude 任意包含目标文件中的所有代码,而不用担心页面上还有什么。这不是你想要的。 extends header.pug 允许 header.pug 文件呈现自身,以及您将使用 block 定义的附加代码。因此,您必须将代码更改为如下所示:

    header.pug

    doctype
    html
        head
            meta(charset='utf-8')
            title Express Guestbook
            link(href="to/bootstrap.min.css", rel="stylesheet")
    
        body.container
            h1 Express Guestbook
                a.btn.btn-primary.pull-right(href="/new-entry") Write in Guestbook
    
            //- putting this div here so that whatever code 'include'-s this 
            //- header, will be a child of this div
            div
                block content
    

    block content 行将替换为您选择将block content 定义为另一个 Pug 文件中的任何内容。这在下一个文件中更有意义。

    404.pug

    extends header.jade
    
    //- Everything that is a child of "block content" replaces the "block content"
    //- from our "header.pug" file
    block content
        h2 404! Page not found
    

    因此生成的 HTML 输出是...

    <!DOCTYPE html>
    <html>
      <head>
        <meta charset="utf-8">
        <title>Express Guestbook</title>
        <link href="to/bootstrap.min.css" rel="stylesheet">
      </head>
      <body class="container">
        <h1>Express Guestbook<a href="/new-entry" class="btn btn-primary pull-right">Write in Guestbook</a></h1>
        <div>
          <h2>404! Page not found</h2>
        </div>
      </body>
    </html>
    

    【讨论】:

    • 这太棒了!我确实阅读了文档中的概念,但现在更有意义了!
    • 很高兴我能帮上忙!欢迎阅读更多关于extend 工作原理here
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-02-21
    • 2022-08-14
    • 1970-01-01
    • 1970-01-01
    • 2020-04-01
    • 2017-06-27
    相关资源
    最近更新 更多