Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Adding file locations to templates #1482

Open
KonnorRogers opened this issue Jan 30, 2025 · 0 comments
Open

Adding file locations to templates #1482

KonnorRogers opened this issue Jan 30, 2025 · 0 comments

Comments

@KonnorRogers
Copy link

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?

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

1 participant