arefm / point-of-view

Template rendering plugin for Fastify

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

point-of-view

js-standard-style Build Status

Templates rendering plugin support for Fastify.

point-of-view decorates the reply interface with the view method for manage view engines that can be used to render templates responses.

Currently supports the following templates engines:

In production mode, point-of-view will heavily cache the templates file and functions, while in development will reload every time the template file and function.

Note that at least Fastify v0.13.1 is needed.

Benchmarks

The benchmark were run with the files in the benchmark folder with the ejs engine.
The data has been taken with: autocannon -c 100 -d 5 -p 10 localhost:3000

  • Express: 8.8k req/sec
  • Fastify: 15.6k req/sec

Install

npm install point-of-view --save

Usage

const fastify = require('fastify')()

fastify.register(require('point-of-view'), {
  engine: {
    ejs: require('ejs')
  }
})

fastify.get('/', (req, reply) => {
  reply.view('/templates/index.ejs', { text: 'text' })
})

fastify.listen(3000, err => {
  if (err) throw err
  console.log(`server listening on ${fastify.server.address().port}`)
})

If you want to set a fixed templates folder, or pass some options to the template engines:

fastify.register(require('point-of-view'), {
  engine: {
    ejs: require('ejs')
  },
  templates: 'templates',
  options: {}
})

If you want to omit view extension, you can add includeViewExtension property as following:

fastify.register(require('point-of-view'), {
  engine: {
    ejs: require('ejs')
  },
  includeViewExtension: true
});

fastify.get('/', (req, reply) => {
  reply.view('/templates/index', { text: 'text' })
})

Note that to use include files with ejs you also need:

// get a reference to resolve
const resolve = require('path').resolve
// other code ...
// in template engine options configure how to resolve templates folder
  options: {
    filename: resolve('templates')
  }

and in ejs template files (for example templates/index.ejs) use something like:

<% include templates/header.ejs %>

Acknowledgements

This project is kindly sponsored by:

License

Licensed under MIT.

About

Template rendering plugin for Fastify

License:MIT License


Languages

Language:JavaScript 96.3%Language:HTML 3.7%