Skip to content

Adding file locations to templates #1482

@KonnorRogers

Description

@KonnorRogers

I'm not quite sure where to put this, but previously in EJS I had a fileLoader hook for adding "preambles" and "postambles" to file renderings. Does nunjucks have an equivalent?

EJS:

import ejs from "ejs"

let ejsFileLoader = function (filePath: string) {
  const preamble = `<!-- template_start: ${path.relative(getRootDir(), filePath)} -->`
  const postamble = `<!-- template_end: ${path.relative(getRootDir(), filePath)} -->`
  
  return preamble + fs.readFileSync(filePath) + postamble;
};

ejs.fileLoader = ejsFileLoader

The best I came up with for Nunjucks is the following:

const render = nunjucks.render
nunjucks.render = function (file: string, ...args: any[]) {
  const preamble = `<!-- template_start: ${path.relative(getRootDir(), file)} -->`
  const postamble = `<!-- template_end: ${path.relative(getRootDir(), file)} -->`
  
  return preamble + render.call(nunjucks, file, ...args) + postamble
}

but that feels wrong. Am I missing something obvious using the FileLoader or Environment APIs?

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions