Template inheritance
All pages of a site share the same skeleton: doctype, a head with styles, a body with a header and a footer. Only the middle changes. Template inheritance lets you describe the skeleton once in a layout, and in each page fill in only the parts that change — the blocks.
A layout with a block
Create the file src/layout.pug:
doctype html
html(lang="en")
head
meta(charset="utf-8")
title Morning Café
body
main
block contentThe line block content is the place a page will fill in. content is just a name; you choose it. The layout itself is not built into an HTML file of its own.
A page based on the layout
Replace the contents of src/index.pug:
extends layout.pug
block content
h1 Fresh coffee every day
p Come for breakfast from 8:00.extends names the layout, and block content with indented lines below says what to fill the block of the same name with. After npm run build, dist/index.html contains the whole skeleton from the layout, with the page markup inside main:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Morning Café</title>
</head>
<body>
<main>
<h1>Fresh coffee every day</h1>
<p>Come for breakfast from 8:00.</p>
</main>
</body>
</html>Several blocks and default content
A layout can have as many blocks as you like. If there is markup under a block in the layout, it is the default: it stays if the page does not override the block. Add blocks for the tab title and for styles to src/layout.pug:
doctype html
html(lang="en")
head
meta(charset="utf-8")
block title
title Morning Café
block head
link(rel="stylesheet" href="style.css")
body
main
block contentA page can override title and leave head alone — then the shared stylesheet stays there.
append and prepend
Sometimes a page needs to add to a block rather than replace it — for example, link its own CSS without losing the shared one. That is what block append (add to the end) and block prepend (add to the start) do, or for short append and prepend. In src/index.pug:
extends layout.pug
block title
title Home — Morning Café
append head
link(rel="stylesheet" href="home.css")
block content
h1 Fresh coffee every dayThe tab title is replaced, and head now has both stylesheets, the shared one and the home page one:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Home — Morning Café</title>
<link rel="stylesheet" href="style.css">
<link rel="stylesheet" href="home.css">
</head>
<body>
<main>
<h1>Fresh coffee every day</h1>
</main>
</body>
</html>| In the page | What happens to the block |
|---|---|
block name | The content is replaced |
append name | Added to the end |
prepend name | Added to the start |
Common mistake
Writing page markup outside blocks:
extends layout.pug
h1 MenuIn a template with extends, only blocks and mixins may appear at the top level, so the build stops with the error "Only named blocks and mixins can appear at the top level of an extending template". Put all page markup inside block content or another block.