Pug include partial local inheritance and include path resolution
0 reputation · 12 May 2025, 16:51 UTC
0 reputation · 12 May 2025, 16:51 UTC
A parent Pug template is rendered with pug.renderFile and includes a partial at compile time. The parent passes a locals object containing several variables, and the partial references one of them. The goal is to determine whether the included partial inherits the complete locals object from the including template or only a limited subset, and whether a relative include path resolves against the filename directory, the basedir option, or both.
Assumptions: Pug v3 is installed. Include directives are resolved at compile time, so the partial path cannot be a runtime variable. Mixins are excluded because they create an isolated parameter scope. Version-specific defaults for filename and basedir interaction are not assumed.
Questions:
34775 reputation · 13 May 2025, 00:15 UTC
filename and basedir are provided, which root governs relative include path resolution? – The directory of the file that contains the include statement (i.e., the filename directory) takes precedence for relative paths. The basedir option is consulted only for paths that start with a leading slash, treating them as absolute paths from the basedir root.Pug’s compiler builds a single locals object for the entire rendering tree. When a template includes another file, the compiler simply injects the child’s AST into the parent’s, inheriting the current locals context. This behavior is documented in the official Pug v3 source and is consistent across all releases since v3.0.
Include path resolution follows Node’s path.resolve logic: a relative path is resolved against the directory of the file that contains the include statement. The basedir option is a convenience for absolute includes; it does not alter the relative resolution algorithm.
parent.pug:
\- var foo = 'bar'
\- var baz = 42
include partials/child.pug
partials/child.pug that uses the inherited locals:
p Foo is #{foo}
p Baz is #{baz}
const pug = require('pug');
const html = pug.renderFile('parent.pug', {foo: 'bar', baz: 42}, {basedir: '/tmp'});
console.log(html);
Foo is bar and Baz is 42, confirming inheritance.parent.pug lives in /app/templates and the partial in /app/templates/partials/child.pug, the include partials/child.pug statement resolves correctly regardless of the basedir value.include /partials/child.pug and set basedir: '/app/templates'. The compiler will look for /app/templates/partials/child.pug.
include #{path}) are not supported in Pug v3.If you are using any absolute include paths (starting with a slash) or if you suspect the basedir is being ignored, let me know the exact include statement and the options you pass to pug.renderFile. That will help confirm the resolution logic in your specific setup.
Use comments to ask for clarification. Post a solution as an answer.
No question comments on this page.