queckezz / koa-views

Template rendering middleware for koa (hbs, swig, pug, anything! :sparkles:)
MIT License
710 stars 87 forks source link

Support for layout template files & Code clean-up #165

Open kellnerd opened 2 years ago

kellnerd commented 2 years ago

This PR adds support for a layout file which can be used as a shared top-level template to have a common page structure into which the rendered template will be inserted. This is useful for template engines which do not have native support for layout files, e.g. EJS.

Layout support can be enabled by passing the name of a layout file to the rendering context/state in the layout property. This layout template will then have access to the same state as the current template, for which render() has been called. Instead of directly returning the resulting HTML of the current template, it will be passed to the layout in the body property and the resulting HTML of the layout will be returned.

Example:

await ctx.render('foo', { layout: 'simple_layout', title: 'Hello world!' })

foo.ejs:

<h1><%= title %></h1>

simple_layout.ejs:

<!DOCTYPE html>
<html>

<head>
  <meta charset="UTF-8">
  <title><%= title %></title>
</head>

<body>
<%- body %>
</body>

</html>

The PR also updates the type definitions, drops an unused dependency and refactors the code to use async/await (requires node v7.6+ which koa v2 needs anyway) instead of promise chaining to make the code easier to understand (or to extend, as I did here). See the individual commit messages for details.

kellnerd commented 2 years ago

Is this project still maintained? If there's anything I can do to improve this PR, just let me know. And if the layout template file feature is out of scope for this package, I can also drop the two commits with the refactoring and the feature addition. The remaining changes are still worth merging IMO.

queckezz commented 2 years ago

@kellnerd Sorry, I stopped using koa a long time ago and I cannot support the package with my current capacity. Would you like to step in as a maintainer? At a quick glance, the PR looks solid and makes total sense.

what do you guys think @int64ago & @niftylettuce?

kellnerd commented 2 years ago

Thank you for the honest response @queckezz. I haven't published anything on npm so far, so I'm not sure whether I would be a good maintainer. But given that I'm using the package for at least one project, I will read the npm docs and try my best.

As this PR gives the layout property of the rendering context a special meaning, this change probably requires a major version bump and a mention in the README, right?

titanism commented 1 year ago

We are maintaining a new fork at https://github.com/ladjs/koa-views of this project - feel free to submit PR/work there. Thank you.