1.0.5 • Published 3 years ago

simple-ejs v1.0.5

Weekly downloads
9
License
MIT
Repository
-
Last release
3 years ago

simple-ejs

A simply packaged ejs render, originally designed to replace the koa-ejs module, but can also be used in almost any framework.

This is not a very rigorous project. If you want to use it in a production environment, you must fully understand the code before using it.

Why?

The koa-ejs module binds the generated render function to the app.context property of the Koa framework for access at runtime. This method does not support TypeScript well (the type of ctx.render() during compilation check It is any, which is not the case), if a routing plug-in such as koa-router is used, the middleware called in the routing cannot know the existence of ctx.render(), causing the compilation to fail.

In addition, if there are multiple EJS situations that require different configurations in the project, the koa-ejs module cannot provide good support, because the process of passing options to build the ctx.render() function can only be done once. The native ejs module is too complicated to implement in each middleware separately.

In short, I need a renderer that can correctly infer the type and is flexible without being bound to a ctx object.

Howto?

installation:

npm install simple-ejs # or use yarn instead of npm
yarn add simple-ejs

Example:

import Koa from'koa'
import Router from'koa-router'
import {Render} from'simple-ejs'
import {join} from'path'

const app = new Koa()
const router = new Router({
    prefix:'/ejs'
})
// Generate renderer
const ejs = new Render({
    prefix: join(process.cwd(),'views'),
    extendName:'.ejs'
    rmWhitespace: true,
    cache: true
})

router.get('/:username', async (ctx, next) => {
    const username = ctx.params.username
    const data = {
        title: `hello, ${username}`,
        paragraphs: [
            `This is a page rendered by ejs.`,
            `This page is provided by Koa and koa-ejs-lite.`,
            `Server side info: Node ${process.version} running on ${process.platform}`
        ]
    }
    // Use renderer
    ctx.body = await ejs.render('index', data)
})

app.use(router.routes())

export default app

API

  • Render: A class that directly exported from the module, and the renderer object ejs is obtained after instantiation.
    • @param option extends from the Option class of ejs, adding two parameters:
      • prefix: string EJS file storage path
      • extendName?: string Limit the extension of EJS file, the default value is'.ejs', if not limited, set to''
  • ejs: The instantiated Render object contains an accessible property, namely the render asynchronous function
    • render(filename: string, data: Data): Promise:
      • @param filename: string input file name, with or without extension, if the extension is inconsistent with the pre-specified extension, the specified extension will be appended during actual access
      • @param data: Data: The Data class of ejs, which is an instance of the Object class.

Since the final render function is asynchronous, whether it is used in Koa or Express frameworks, it must be called in asynchronous middleware, and attention should be paid to error handling, for example:

// Express
app.use('/:page/:username', async (req, res) => {
    const page = req.params.page
    const username = req.params.username
    try {
        const html = await ejs.render(page, {username })
        res.send(html)
    } catch(err) {
        errorLog(err)
        res.sendFile(__dirname +'/static/404.html')
    }
})
// Koa
app.use(async (ctx,next) => {
    try {
        ctx.body = await ejs.render('index', {status: db.status() })
    } catch(err) {
        errorLog(err)
        ctx.status = 404
        ctx.body ='<h1>404 Not Found</p>'
    }
}) 
1.0.5

3 years ago

1.0.4

3 years ago

1.0.3

3 years ago

1.0.2

3 years ago

1.0.1

3 years ago

1.0.0

3 years ago