forked from strawbrary/koa-nunjucks-2
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathindex.js
85 lines (70 loc) · 2.31 KB
/
index.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
/*!
* koa-nunjucks-2
* Copyright (c) 2015 strawbrary
* MIT Licensed
*/
'use strict';
var _ = require('lodash');
var copy = require('copy-to');
var path = require('path');
var nunjucks = require('nunjucks');
/**
* @type {Object}
*/
const defaultSettings = {
autoescape: true, // Whether variables are automatically escaped in templates
dev: false, // Determines if full stack traces from the origin of the error are shown*
ext: 'html', // Specifying an extension allows you to omit extensions in this.render calls
lstripBlocks: false, // Whether to strip leading whitespace from blocks
noCache: false, // Whether to disable template caching
path: '', // Path to the templates
throwOnUndefined: false, // Throw an error if a template variable is undefined
trimBlocks: false, // Whether to trim first newline at end of blocks
watch: true, // Reload templates when they are changed
writeResp: true // Whether to write the rendered output to response.body
};
/**
* Config options which belong to this package, not Nunjucks itself
* @type {Array.<string>}
* @const
*/
const packageConfigOptions = [
'ext',
'path',
'writeResp'
];
/**
* @param {Object=} opt_config
*/
exports = module.exports = function(opt_config) {
var config = {};
if (config) {
config = opt_config;
}
copy(defaultSettings).to(config);
config.path = path.resolve(process.cwd(), config.path);
if(config.ext !== false) config.ext = '.' + config.ext.replace(/^\./, '');
// Strip the package specific config options before passing to Nunjucks
var nunjucksConfig = _.omit(config, packageConfigOptions);
var env = nunjucks.configure(config.path, nunjucksConfig);
/**
* Main function to be placed on app.context
* @param {string} view
* @param {Object=} opt_context
* @param {Function=} opt_callback
* @returns {string}
*/
var render = function*(view, opt_context, opt_callback) {
var context = _.merge({}, this.state, opt_context);
if(config.ext !== false) view += config.ext;
var html = env.render(view, context, opt_callback);
if (config.writeResp) {
this.type = 'html';
this.body = html;
}
return html;
};
// Expose the Nunjucks Environment
render.env = env;
return render;
};