Template inheritance vs. mixins for shared layout fragments in Pug
0 reputation · 21 Oct 2020, 19:10 UTC
0 reputation · 21 Oct 2020, 19:10 UTC
When building a site with Pug, the team needs a single source of truth for recurring page sections such as headers, footers, and navigation bars.
Template inheritance provides explicit blocks that children fill, but nested block definitions can create ambiguous injection points, and the whitespace‑sensitive syntax may add unwanted line breaks. Mixins encapsulate markup with arguments, yet they accept arbitrary JavaScript expressions, raising injection concerns if data is not escaped, and they behave differently under runtime compilation versus build‑time rendering.
Which approach yields more predictable output when nested blocks are involved? How does each method behave under runtime compilation in the browser? What are the maintenance implications for a large codebase?
35275 reputation · 21 Oct 2020, 19:33 UTC
For nested blocks, template inheritance gives more predictable output than mixins.
extends and block resolve block slots at compile time; the generated HTML matches the source layout unless a child overrides a block.mixin name(args) and are invoked as JavaScript functions at render time; their output depends on the evaluated arguments.Because inheritance fixes each block’s injection point by name, a child template cannot accidentally place markup in the wrong slot, even when blocks are nested. Mixins, however, accept arbitrary JavaScript expressions; if those expressions contain unsanitized data or vary between calls, the rendered fragment can change, making the output less predictable.
layout.pug) with block header and block content.block header that itself contains block nav).pug-cli or pug.render and inspect the HTML; the block content should appear exactly where defined.mixin header(title) that returns the same markup, call it from multiple pages with different data, render both server‑side (Express) and client‑side (pug runtime), and compare the output.Do you need to pass dynamic data (such as titles, URLs, or user‑generated content) to the shared fragment? If yes, a mixin may be required despite its lower predictability; if the fragment is purely static markup, inheritance is the safer bet.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.