Skip to content

Support custom template locals - #167

Open
vibhor-aggr wants to merge 2 commits into
expressjs:masterfrom
vibhor-aggr:feat/pass-request-response-template
Open

Support custom template locals#167
vibhor-aggr wants to merge 2 commits into
expressjs:masterfrom
vibhor-aggr:feat/pass-request-response-template

Conversation

@vibhor-aggr

@vibhor-aggr vibhor-aggr commented Jun 17, 2026

Copy link
Copy Markdown

Fixes #42.

This adds a way to pass additional data into custom template functions without exposing req or res to the renderer:

  • options.locals provides static template locals.
  • req.locals provides request-scoped locals from upstream middleware.
  • Required serve-index locals are merged last so built-in rendering fields such as directory, fileList, path, style, and viewName cannot be overridden accidentally.

This preserves the existing template callback signature and keeps rendering independent from direct request/response side effects.

Verification:

  • ./node_modules/.bin/mocha --reporter spec --check-leaks test/ --grep 'locals'
  • npm test
  • npm run lint
  • git diff --check master..HEAD

@krzysdz krzysdz left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

I just read #42 and it seems clear to me that this solution is not desired:

Hi! The point of the rendering is to be independent of any interaction and creating side-effects from the request, thus why we do not provide the req and res.
Originally posted by @dougwilson in #42 (comment)

An alternative has been provided in #42 (comment)

@vibhor-aggr vibhor-aggr changed the title Pass request and response to template functions Support custom template locals Jul 4, 2026
@vibhor-aggr

Copy link
Copy Markdown
Author

Thanks for the review. I updated the approach to avoid passing req or res into the template function.

The current diff now follows the alternative pattern from #42: callers can provide static options.locals, and middleware can attach request-scoped data to req.locals. The template function still receives only (locals, callback), and serve-index merges its required locals last so the built-in rendering fields cannot be overridden by custom data.

I also updated the README and added focused coverage for:

  • options.locals
  • req.locals
  • request locals overriding static locals
  • required serve-index locals overriding custom locals

Local verification passed with the commands listed in the PR body.

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

Successfully merging this pull request may close these issues.

Provide method to add to template locals

2 participants