npm package discovery and stats viewer.

Discover Tips

  • General search

    [free text search, go nuts!]

  • Package details

    pkg:[package-name]

  • User packages

    @[username]

Sponsor

Optimize Toolset

I’ve always been into building performant and accessible sites, but lately I’ve been taking it extremely seriously. So much so that I’ve been building a tool to help me optimize and monitor the sites that I build to make sure that I’m making an attempt to offer the best experience to those who visit them. If you’re into performant, accessible and SEO friendly sites, you might like it too! You can check it out at Optimize Toolset.

About

Hi, 👋, I’m Ryan Hefner  and I built this site for me, and you! The goal of this site was to provide an easy way for me to check the stats on my npm packages, both for prioritizing issues and updates, and to give me a little kick in the pants to keep up on stuff.

As I was building it, I realized that I was actually using the tool to build the tool, and figured I might as well put this out there and hopefully others will find it to be a fast and useful way to search and browse npm packages as I have.

If you’re interested in other things I’m working on, follow me on Twitter or check out the open source projects I’ve been publishing on GitHub.

I am also working on a Twitter bot for this site to tweet the most popular, newest, random packages from npm. Please follow that account now and it will start sending out packages soon–ish.

Open Software & Tools

This site wouldn’t be possible without the immense generosity and tireless efforts from the people who make contributions to the world and share their work via open source initiatives. Thank you 🙏

© 2024 – Pkg Stats / Ryan Hefner

ejs-with-layouts

v0.0.2

Published

Adds support for Nested Layouts to EJS templates. Compatible with Express.js.

Downloads

2

Readme

EJS With Layouts

Render EJS templates with Nested Layouts. Supports Express servers.

Usage

The module is set up for use with express servers.

Assume you have an Express app with a folder structure that looks like this:

├── server.js
├── views
│   ├── pages
│   │   └── index.ejs
│   │
│   └── layouts
│       ├── head.ejs
│       └── app-shell.ejs
│
├── README.md
├── package.json
└── .gitignore

First, set this module's exported function as the view engine for your app's EJS templates.

// server.js
const app = require('express')();
const path = require('path');
const ejsRenderer = require('ejs-with-layouts');

app.engine('ejs', ejsRenderer); // add this line
app.set('view engine', 'ejs');
//...

Then in your request handlers, call res.render() as you normally would.

// ...
// server.js
app.set('views', path.join(__dirname, 'views'));

app.get('/', function (req, res) {
	res.render('pages/index', {
		name: 'Tinky Winky',
		path: req.path,
	});
});

const port = 3000;
app.listen(port);

Finally, in your views, call the extend function to have the view rendered within the layout you specify.

<%# views/pages/index.ejs %>

<% extend('../layouts/app-shell', { title: 'Hello, world!' }) %>

<h1>Hello, <%= name || 'World' %>!</h1>
<p>You are here: <i><%= path %></i></p>
<%# views/layouts/app-shell.ejs %>

<% extend('./head', { name: 'Laa Laa' }) %>

<main>
	<%- content %>
</main>

<footer>
	<address>
		Goodbye, <%= name %>.
		💖, <a href="https://feranmi.dev">Dipsy</a>.
	</address>
</footer>
<%# views/layouts/head.ejs %>

<!DOCTYPE html>
<html>
	<head>
		<title>
			<%= title %>
		</title>
		<meta name="description" content="Greetings for <%= name %>.">
	</head>
	<body>
		<%- content %>
	</body>
</html>

That's all. Now when your server receives a get request at the root path /, it will respond with the following HTML.

<!-- Final Output -->
<!DOCTYPE html>
<html>
	<head>
		<title>
			Hello, world!
		</title>
		<meta name="description" content="Greetings for Laa Laa.">
	</head>

	<body>
		<main>
			<h1>Hello, Tinky Winky!</h1>
			<p>You are here: <i>/</i></p>
		</main>

		<footer>
			<address>
				Goodbye, Tinky Winky.
				💖, <a href="https://feranmi.dev">Dipsy</a>.
			</address>
		</footer>
	</body>
</html>

Passing Data to Layouts

The example above demonstrates how data is passed to all layouts in the chain.

  • The data passed when calling res.render() will be available to all layouts in the chain.
  • Any additional data passed when extending a particular layout will be available within that layout and any higher-level layout it extends, all the way to the top of the chain.
  • Values passed when calling extend() will override any preexisting value of the same name, and persist further up the chain. This explains why the name variable resolved to "Laa Laa" in head.ejs, but rendered "Tinky Winky" in the lower two templates.

Notes:

  • The call to extend() in your .ejs templates can be surrounded with any combination of (<% or <%-) and (%> or -%>), since it does not return a value.
  • The content variable should always be rendered with <%- content %> in all layout templates. This prevents the HTML tags from being escaped.
  • The signature of extend is: extend(layout[, data]), where layout is a string containing the path to the layout template, and data is an object containing additional variables to be made available to the layout template.

How It Works

This module exports a single function, which can be used to render EJS templates. It is ready to be used as an Express engine. It has the following signature.

/**
 * @param {string} viewPath - The file path of the view to be rendered.
 * @param {object} viewData - Object containing variables to be exposed to the template(s).
 * @param {function(Error, string?)} onRenderingCompleted - Callback function used to pass the
 *  rendered HTML string to the Express Server after rendering is completed.
 */
function renderEjsWithLayouts(viewPath, viewData, onRenderingCompleted) {
  //...
}

It injects a function named extend into the view. The extend function takes the rendered content of the current view and passes it into the specified layout as a variable named content. So the layout template can render the content of the view wrapped in some boilerplate HTML.

If the layout also calls extend, then the higher-level layout will be applied recursively. This allows for the creation of nested layouts.

Currently, only one layout is supported per file. If extend is called more that once in a single file, only the last call will be used.

License

This project is released under the MIT license.