PragmaticView Express
PragmaticView plugin for Express.
npm install --save pragmatic-view pragmatic-view-express
Typed for Typescript
Getting started
Adding custom templating engine to Express is quite inconvenient. That's why PragmaticView offers helper method that takes care of everything. Just pass express app to the helper method.
// ES6
import pragmaticView from 'pragmatic-view-express';
// CommonJS
const pragmaticView = require('pragmatic-view-express').default;
// creating express app
const app = express();
pragmaticView(app);
app.get('/', (req, res) => {
res.render('home');
});
app.listen(8080);
You may want to pass config as additional argument.
Config:
templateExtension
extension of template files (.jsx
,.tsx
or.pv
), default.pv
templateDir
directory of templates (automaticaly setsapp.set('views', './directory')
),defaultLayout
path to default layout template, relative is evalutaed accordint totemplateDir
registerOptions
additional template transpilation options, learn more
pragmaticView(app, {
templateDir: path.resolve(process.cwd(), './views'),
templateExtension: '.jsx'
});
Rendering templates
Templates are rendered through express' response.render
method that accept two argument. First argument is relative path to the template without extansion (realtive to Express' template directory set either in templateDir
or app.set('views', './directory')
). Second argument is either context
object or options
object.
app.get('/aboutus', (req, res) => {
let context = {
title: 'My page'
}
res.render('home', context);
});
options
object can include
layout
realative path (works like path to template), iffalse
is passed instead of string, no layout is usedcontext
context object
// Rednering with different layout
app.get('/aboutus', (req, res) => {
let context = {
title: 'My page'
}
res.render('home', {
layout: 'bluelayout',
context: {
title: 'My page'
}
});
});
// Rednering without layout
app.get('/aboutus', (req, res) => {
let context = {
title: 'My page'
}
res.render('home', {
layout: false,
context: {
title: 'My page'
}
});
});