forked from warmrobot/nunjucks-html-loader
-
Notifications
You must be signed in to change notification settings - Fork 0
/
index.js
97 lines (79 loc) · 2.44 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
86
87
88
89
90
91
92
93
94
95
96
97
const utils = require('loader-utils')
const fs = require('fs')
const path = require('path')
const nunjucks = require('nunjucks')
const i18n = require('i18n')
const NunjucksLoader = nunjucks.Loader.extend({
// Based off of the Nunjucks 'FileSystemLoader'
init: function(searchPaths, sourceFoundCallback) {
this.sourceFoundCallback = sourceFoundCallback
if (searchPaths) {
searchPaths = Array.isArray(searchPaths) ? searchPaths : [searchPaths]
// For windows, convert to forward slashes
this.searchPaths = searchPaths.map(path.normalize)
} else {
this.searchPaths = ['.']
}
},
getSource: function(name) {
let fullpath = null
const paths = this.searchPaths
for (var i = 0; i < paths.length; i++) {
const basePath = path.resolve(paths[i])
const p = path.resolve(paths[i], name)
// Only allow the current directory and anything
// underneath it to be searched
if (p.indexOf(basePath) === 0 && fs.existsSync(p)) {
fullpath = p
break
}
}
if (!fullpath) {
return null
}
this.sourceFoundCallback(fullpath)
return {
src: fs.readFileSync(fullpath, 'utf-8'),
path: fullpath,
noCache: this.noCache,
}
},
})
module.exports = function(content) {
this.cacheable()
const currentRequest = utils.getCurrentRequest(this)
const currentLocale = currentRequest.substr(currentRequest.length - 6, 2)
const callback = this.async()
const opt = utils.getOptions(this) || {}
const nunjucksSearchPaths = opt.searchPaths
const nunjucksContext = {
activeLocale: currentLocale,
...(opt.context || {}),
}
const config = opt.configure || {}
const configureEnvironment = opt.configureEnvironment || function(env) {}
const i18nOptions = opt.i18n
const loader = new NunjucksLoader(
nunjucksSearchPaths,
function(path) {
this.addDependency(path)
}.bind(this)
)
const nunjEnv = new nunjucks.Environment(loader, config)
if (i18nOptions) {
i18n.configure({ ...i18nOptions, defaultLocale: currentLocale })
nunjEnv.addGlobal(
'__',
!i18nOptions.transformFunc
? i18n.__
: function(key) {
let result = i18n.__(...arguments)
return i18nOptions.transformFunc(key, result)
}
)
}
configureEnvironment(nunjEnv)
const template = nunjucks.compile(content, nunjEnv)
const html = template.render(nunjucksContext)
callback(null, html)
}