UNPKG

2.97 kBMarkdownView Raw
1# Grunt task for rendering nunjucks` templates to HTML
2
3[![NPM version](https://badge.fury.io/js/grunt-nunjucks-2-html.png)](http://badge.fury.io/js/grunt-nunjucks-2-html)
4
5## Getting start
6
7If you haven't used [Grunt](http://gruntjs.com/) before, be sure to check out the [Getting Started](http://gruntjs.com/getting-started) guide.
8
9Once plugin has been installed include it in your `Gruntfile.js`
10
11```javascript
12grunt.loadNpmTasks('grunt-nunjucks-2-html');
13```
14
15## Usage examples
16
17Task targets and options may be specified according to the grunt [Configuring tasks](http://gruntjs.com/configuring-tasks) guide.
18
19```javascript
20nunjucks: {
21 options: {
22 data: grunt.file.readJSON('data.json'),
23 paths: 'templates'
24 },
25 render: {
26 files: {
27 'index.html' : 'index.html'
28 }
29 }
30}
31```
32
33`templates/index.html` (relative to the gruntfile) is now compiled with `data.json`!
34
35```javascipt
36nunjucks: {
37 options: {
38 data: grunt.file.readJSON('data.json')
39 },
40 render: {
41 files: [
42 {
43 expand: true,
44 cwd: "bundles/",
45 src: "*.html",
46 dest: "build/",
47 ext: ".html"
48 }
49 ]
50 }
51```
52
53You'll get a set of html files in `build` folder.
54
55## Options
56
57### data
58
59Read JSON from file using `grunt.file.readJSON` or specify object just inside your `Gruntfile`.
60
61### preprocessData
62
63You should specify a function to construct each data object for every of your templates. Execution context for the function would be a [grunt file object](http://gruntjs.com/api/inside-tasks#this.files). If you specify a data option it would be passed inside the function as an argument.
64
65For instance, you could include name of the file inside an every data object
66
67```javascipt
68
69var path = require('path');
70
71...
72
73nunjucks: {
74 options: {
75 preprocessData: function(data) {
76 var page = path.basename(this.src[0], '.html');
77 var result = {
78 page: page,
79 data: data
80 };
81 return result;
82 },
83 data: grunt.file.readJSON('data.json')
84 },
85 render: {
86 files: [
87 {
88 expand: true,
89 cwd: "bundles/",
90 src: "*.html",
91 dest: "build/",
92 ext: ".html"
93 }
94 ]
95 }
96```
97
98### paths
99
100You could specify root path for your templates, `paths` would be set for [nunjucks' configure](http://mozilla.github.io/nunjucks/api#configure)
101
102
103### Customizing Syntax
104
105If you want different tokens than {{ and the rest for variables, blocks, and comments, you can specify different tokens as the tags option:
106
107```javascipt
108nunjucks: {
109 options: {
110 tags: {
111 blockStart: '<%',
112 blockEnd: '%>',
113 variableStart: '<$',
114 variableEnd: '$>',
115 commentStart: '<#',
116 commentEnd: '#>'
117 },
118 data: grunt.file.readJSON('data.json')
119 },
120 render: {
121 files: [
122 {
123 expand: true,
124 cwd: "bundles/",
125 src: "*.html",
126 dest: "build/",
127 ext: ".html"
128 }
129 ]
130 }
131```
132
133
134Nice!