UNPKG

2.72 kBMarkdownView Raw
1[![Build Status](https://travis-ci.org/giaman/gulp-nunjucks-html.svg?branch=master)](https://travis-ci.org/giaman/gulp-nunjucks-html)
2
3Render [Nunjucks](http://mozilla.github.io/nunjucks) templates to HTML.
4
5## Usage
6
7```js
8var nunjucks = require('gulp-nunjucks-html');
9
10gulp.task('nunjucks', function() {
11 return gulp.src('src/templates/*.html')
12 .pipe(nunjucks({
13 locals: {
14 username: 'James'
15 },
16 searchPaths: ['src/templates']
17 }))
18 .pipe(gulp.dest('dist'));
19});
20```
21
22### Error handling
23
24This plugin will emit an error for cases such as invalid Nunjucks syntax or missing imported files. If uncaught, the error will crash Gulp.
25
26You will need to attach a listener for the error event emitted by the stream:
27
28```js
29gulp.task('nunjucks', function() {
30 return gulp.src('src/templates/*.html')
31 .pipe(nunjucks({
32 searchPaths: ['src/templates']
33 }))
34 .on('error', function(err) {
35 // err is the error thrown by the Nunjucks compiler.
36 })
37 .pipe(gulp.dest('dist'));
38});
39```
40
41### Use with [gulp-data](https://www.npmjs.org/package/gulp-data)
42
43With `gulp-data` you can pass additional context to the Nunjucks compiler.
44
45For example, to get the data from a JSON file:
46
47```js
48gulp.task('nunjucks', function() {
49 return gulp.src('src/templates/contact.html')
50 .pipe(data(function(file) {
51 return require('./metadata/' + path.basename(file.path) + '.json');
52 }))
53 .pipe(nunjucks({
54 locals: {
55 name: 'James'
56 }
57 }))
58 .pipe(gulp.dest('dist'));
59});
60```
61
62This will merge the content of the JSON file with the `locals` hash. Note that `gulp-data` has precedence over `locals`.
63
64## Options
65
66#### searchPaths
67
68Type: `Array`
69
70Default: `[]`
71
72A list of paths to look for templates (see [FileSystemLoader](http://mozilla.github.io/nunjucks/api.html#filesystemloader)).
73Can also be a single path for where templates live, and it defaults to the current working directory.
74
75#### locals
76
77Type: `Object`
78
79Default: `{}`
80
81The `context` object passed to [nunjucks.renderString](http://mozilla.github.io/nunjucks/api.html#renderstring).
82
83#### autoescape
84
85Type: `Boolean`
86
87Default: `false`
88
89Controls if output with dangerous characters are escaped automatically.
90
91#### setUp
92
93Type: `Function`
94
95Default: `undefined`
96
97Use this function to extend the Nunjuck's `Environment` object, adding custom filters, tags etc.
98
99```js
100gulp.task('html', function() {
101 return gulp.src('src/templates/*.html')
102 .pipe(nunjucks({
103 searchPaths: ['src/templates'],
104 setUp: function(env) {
105 env.addFilter('greet', function(name) {
106 return 'Hello ' + name;
107 });
108 return env;
109 }
110 }))
111 .pipe(gulp.dest('dist'));
112});
113```