0.0.2 • Published 7 years ago
pragmatic-view-express v0.0.2
PragmaticView Express
PragmaticView plugin for Express.
npm install --save pragmatic-view pragmatic-view-expressTyped 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:
templateExtensionextension of template files (.jsx,.tsxor.pv), default.pvtemplateDirdirectory of templates (automaticaly setsapp.set('views', './directory')),defaultLayoutpath to default layout template, relative is evalutaed accordint totemplateDirregisterOptionsadditional 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
layoutrealative path (works like path to template), iffalseis passed instead of string, no layout is usedcontextcontext 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'
}
});
});