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

express-remote-handlebars

v4.0.1

Published

Handlebars view engine for Express which transparently integrates remotely stored templates into your rendering flow

Downloads

1,212

Readme

Express Remote Handlebars

Version License Build Status

Handlebars view engine for Express which transparently integrates remotely stored templates into your rendering flow.

This is useful in an SOA environment where separate applications are responsible for rendering different parts of a site while still requiring one shared layout.

Installation

Install using npm:

$ npm install --save express-remote-handlebars

Tests

Run tests using npm:

$ npm test

Usage

Simple App

A simple application will look as follows:

var express = require('express');
var remoteHandlebars = require('express-remote-handlebars');
var app = express();

app.engine('handlebars', remoteHandlebars({ layout: 'http://localhost/template.handlebars', cacheControl: 'max-age=600, stale-while-revalidate=86400' }));
app.set('view engine', 'handlebars');

app.get('/', function (req, res) {
    res.render('index');
});

In the example above, when res.render() is called the view engine will:

  • Get view and layout from cache if available - Stale items are revalidated in the background (configured using stale-while-revalidate)
  • Otherwise read views/index.handlebars from disk and download http://localhost/template.handlebars
  • Cache local view forever and remote layout for 10 minutes (configured using max-age)
  • Render view and layout (view will be inserted in {{{content}}} placeholder which is configurable using options.placeholder)
  • Send response

Overriding Defaults

You can override instance specific defaults using the options param of res.render():

var express = require('express');
var remoteHandlebars = require('express-remote-handlebars');
var app = express();

app.engine('handlebars', remoteHandlebars({ layout: 'http://localhost/template.handlebars' }));
app.set('view engine', 'handlebars');

app.get('/', function (req, res) {
    res.render('index'); // Will be rendered with default layout
});

app.get('/users/:id', function (req, res) {
    res.render('post', {
        layout: false // Will be rendered without a layout
    });
});

See documentation for all overridable options.

Request in Parallel

In most applications you will get data from a database or REST API before rendering your views.

In order to minimize response times you can fetch layouts together with any other async request using getLayout():

var express = require('express');
var remoteHandlebars = require('express-remote-handlebars').create({ cacheControl: 'max-age=60, stale-while-revalidate=600' });
var app = express();

app.engine('handlebars', remoteHandlebars.engine);
app.set('view engine', 'handlebars');

app.get('/users/:id', function (req, res, next) {
    async.parallel([
        function (callback) {
            // Get user
            User.findOne({ id: req.params.id }, callback);
        },
        function (callback) {
            // Fetch layout
            remoteHandlebars.getLayout('http://localhost/template.handlebars', callback);
        }
    ], function (error, results) {
        if (error) return next(error);
        res.render('index', {
            user: results[0], // User data from database
            layout: results[1] // Compiled Handlebars template from getLayout()
        });
    });
});

Documentation

RemoteHandlebars (options)

Constructor to instantiate a new view engine.

Arguments
  • options.cacheControl - Cache control string (default: max-age=60, stale-while-revalidate=600)

    Use max-age=<seconds> to define when the item will expire.

    Combine with stale-while-revalidate=<seconds> to set the time window after max-age has expired in which the item is marked as stale but still usable. After both max-age and stale-while-revalidate have expired the item will be deleted from cache.

    Examples:

    • no-cache, no-store, must-revalidate - Will be dropped out of cache immediately
    • max-age=600, must-revalidate - Will be cached for 10 minutes and then dropped out of cache
    • max-age=600, stale-while-revalidate=86400 - Will be cached for 10 minutes and then revalidated in the background if the item is accessed again within a time window of 1 day
  • options.helpers - Object with custom helper functions

  • options.layout - URL or request object of layout template (default: false)

  • options.partialsDir - Path(s) to partials (default: views/partials/)

  • options.placeholder - Name of content placeholder in layout (default: content)

  • options.request (options, callback) - Function used to request templates (Default: request)

  • options.size - Maximum number of layouts to cache (default: Infinity)

Examples

Simple:

var remoteHandlebars = require('express-remote-handlebars');
app.engine('handlebars', remoteHandlebars(options));

Factory:

var remoteHandlebars = require('express-remote-handlebars').create(options);
app.engine('handlebars', remoteHandlebars.engine);

Constructor:

var RemoteHandlebars = require('express-remote-handlebars').RemoteHandlebars;
app.engine('handlebars', new RemoteHandlebars(options).engine);

Note: Simple syntax only exposes the view engine. Factory and constructor pattern give access to public methods for more advanced use cases.


render (filePath, options, callback)

Called by Express when running res.render().

Arguments
  • filePath - Path to template
  • options - Context for template (Merged with app.locals and res.locals)
  • options.cache - Toggle caching (This is set by Express via app.enable('view cache') but can also be overridden manually)
  • options.helpers - Object with custom helper functions
  • options.layout - URL, request object or template function
  • options.partialsDir - Path(s) to partials
  • callback (error, rendered) - Called once view with layout has been fully rendered

getLayout ([url, options], callback)

Fetches and compiles a template from remote.

Template is temporarily cached (see max-age, stale-while-revalidate and size) unless disabled.

Arguments
  • url - URL or request object of layout template (optional, default: this.layout)
  • options.cache - Toggle caching (optional, default: true)
  • callback (error, template) - Called once template has been fetched and compiled

getView (filePath, [options], callback)

Reads and compiles a template from disk.

Template is cached forever unless disabled.

Arguments
  • filePath - Path to template
  • options.cache - Toggle caching (optional, default: true)
  • callback (error, template) - Called once template has been read and compiled

getPartials ([partialsDir, options], callback)

Recursively finds and compiles all partials in a directory.

Partials are cached forever unless disabled.

Arguments
  • partialsDir - Path(s) to partials (optional, default: this.partialsDir)
  • options.cache - Toggle caching (optional, default: true)
  • callback (error, partials) - Called once partials have been read and compiled