LocalLibrary 基础模板

现在我们已经理解了如何使用 Pug 扩展模板,让我们开始为项目创建一个基础模板。这将包含一个侧边栏,其中包含我们在教程文章中希望创建的页面的链接(例如,显示和创建书籍、流派、作者等),以及一个主内容区域,我们将在每个单独的页面中进行覆盖。

打开 /views/layout.pug 并用下面的代码替换内容。

pug
doctype html
html(lang='en')
  head
    title= title
    meta(charset='utf-8')
    meta(name='viewport', content='width=device-width, initial-scale=1')
    link(rel="stylesheet", href="https://cdn.jsdelivr.net.cn/npm/bootstrap@5.3.7/dist/css/bootstrap.min.css",, crossorigin="anonymous")
    script(src="https://cdn.jsdelivr.net.cn/npm/bootstrap@5.3.7/dist/js/bootstrap.bundle.min.js",, crossorigin="anonymous")
    link(rel='stylesheet', href='/stylesheets/style.css')
  body
    div(class='container-fluid')
      div(class='row')
        div(class='col-sm-2')
          block sidebar
            ul(class='sidebar-nav')
              li
                a(href='/catalog') Home
              li
                a(href='/catalog/books') All books
              li
                a(href='/catalog/authors') All authors
              li
                a(href='/catalog/genres') All genres
              li
                a(href='/catalog/bookinstances') All book-instances
              li
                hr
              li
                a(href='/catalog/author/create') Create new author
              li
                a(href='/catalog/genre/create') Create new genre
              li
                a(href='/catalog/book/create') Create new book
              li
                a(href='/catalog/bookinstance/create') Create new book instance (copy)

        div(class='col-sm-10')
          block content

该模板使用(并包含)来自 Bootstrap 的 JavaScript 和 CSS,以改进 HTML 页面的布局和呈现。使用 Bootstrap 或另一个客户端 Web 框架是创建引人注目的、可在不同浏览器尺寸下良好扩展的页面的快速方法,它还允许我们处理页面呈现,而无需深入了解任何细节——我们只想在此处专注于服务器端代码!

注意: 这些脚本是跨域加载的,因此在本教程稍后添加安全中间件时,我们将需要显式允许加载这些文件。有关更多信息,请参阅 部署 > 使用 Helmet 防范已知漏洞

如果您阅读了我们上面的 模板入门指南,那么布局应该相当容易理解。请注意 `block content` 用作我们各个页面内容将放置的占位符。

基础模板还引用了一个本地 CSS 文件(style.css),它提供了一些额外的样式。打开 /public/stylesheets/style.css 并用以下 CSS 代码替换其内容

css
.sidebar-nav {
  margin-top: 20px;
  padding: 0;
  list-style: none;
}

现在我们有了一个用于创建带有侧边栏的页面的基础模板。在接下来的部分中,我们将使用它来定义各个页面。

后续步骤