├── .editorconfig ├── .gitattributes ├── .github └── workflows │ └── main.yml ├── .gitignore ├── .npmrc ├── index.js ├── license ├── package.json ├── readme.md └── test.js /.editorconfig: -------------------------------------------------------------------------------- 1 | root = true 2 | 3 | [*] 4 | indent_style = tab 5 | end_of_line = lf 6 | charset = utf-8 7 | trim_trailing_whitespace = true 8 | insert_final_newline = true 9 | 10 | [*.yml] 11 | indent_style = space 12 | indent_size = 2 13 | -------------------------------------------------------------------------------- /.gitattributes: -------------------------------------------------------------------------------- 1 | * text=auto eol=lf 2 | -------------------------------------------------------------------------------- /.github/workflows/main.yml: -------------------------------------------------------------------------------- 1 | name: CI 2 | on: 3 | - push 4 | - pull_request 5 | jobs: 6 | test: 7 | name: Node.js ${{ matrix.node-version }} 8 | runs-on: ubuntu-latest 9 | strategy: 10 | fail-fast: false 11 | matrix: 12 | node-version: 13 | - 20 14 | - 18 15 | steps: 16 | - uses: actions/checkout@v4 17 | - uses: actions/setup-node@v4 18 | with: 19 | node-version: ${{ matrix.node-version }} 20 | - run: npm install 21 | - run: npm test 22 | -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | node_modules 2 | yarn.lock 3 | -------------------------------------------------------------------------------- /.npmrc: -------------------------------------------------------------------------------- 1 | package-lock=false 2 | -------------------------------------------------------------------------------- /index.js: -------------------------------------------------------------------------------- 1 | import {Buffer} from 'node:buffer'; 2 | import {promisify} from 'node:util'; 3 | import nunjucks from 'nunjucks'; 4 | import {gulpPlugin} from 'gulp-plugin-extras'; 5 | 6 | export function nunjucksCompile(data, options = {}) { 7 | return gulpPlugin('gulp-nunjucks', async file => { 8 | const context = { 9 | ...data, 10 | ...file.data, 11 | }; 12 | 13 | const env = options.env ?? new nunjucks.Environment(new nunjucks.FileSystemLoader(file.base), options); 14 | 15 | if (options.filters && !options.env) { 16 | for (const [key, filter] of Object.entries(options.filters)) { 17 | env.addFilter(key, async (...arguments_) => { 18 | const cb = arguments_.pop(); 19 | try { 20 | const result = await filter(...arguments_); 21 | cb(undefined, result); 22 | } catch (error) { 23 | cb(error); 24 | } 25 | }, true); 26 | } 27 | } 28 | 29 | file.contents = Buffer.from(await promisify(env.renderString.bind(env))(file.contents.toString(), context)); 30 | file.extname = '.html'; 31 | 32 | return file; 33 | }); 34 | } 35 | 36 | export function nunjucksPrecompile(options) { 37 | return gulpPlugin('gulp-nunjucks', file => { 38 | const localOptions = {...options}; 39 | localOptions.name = (typeof localOptions.name === 'function' && localOptions.name(file)) || file.relative; 40 | file.contents = Buffer.from(nunjucks.precompileString(file.contents.toString(), localOptions)); 41 | file.extname = '.js'; 42 | return file; 43 | }); 44 | } 45 | -------------------------------------------------------------------------------- /license: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) Sindre Sorhus (https://sindresorhus.com) 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: 6 | 7 | The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. 8 | 9 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. 10 | -------------------------------------------------------------------------------- /package.json: -------------------------------------------------------------------------------- 1 | { 2 | "name": "gulp-nunjucks", 3 | "version": "6.0.0", 4 | "description": "Compile/precompile Nunjucks templates", 5 | "license": "MIT", 6 | "repository": "sindresorhus/gulp-nunjucks", 7 | "funding": "https://github.com/sponsors/sindresorhus", 8 | "author": { 9 | "name": "Sindre Sorhus", 10 | "email": "sindresorhus@gmail.com", 11 | "url": "https://sindresorhus.com" 12 | }, 13 | "type": "module", 14 | "exports": "./index.js", 15 | "engines": { 16 | "node": ">=18" 17 | }, 18 | "scripts": { 19 | "test": "xo && ava" 20 | }, 21 | "files": [ 22 | "index.js" 23 | ], 24 | "keywords": [ 25 | "gulpplugin", 26 | "nunjucks", 27 | "jinja", 28 | "jinja2", 29 | "django", 30 | "template", 31 | "templating", 32 | "view", 33 | "precompile", 34 | "compile", 35 | "html", 36 | "javascript" 37 | ], 38 | "dependencies": { 39 | "gulp-plugin-extras": "^0.2.2", 40 | "nunjucks": "^3.2.4" 41 | }, 42 | "devDependencies": { 43 | "ava": "^5.3.1", 44 | "gulp-data": "^1.3.1", 45 | "p-event": "^6.0.0", 46 | "vinyl": "^3.0.0", 47 | "xo": "^0.56.0" 48 | }, 49 | "peerDependencies": { 50 | "gulp": ">=4" 51 | }, 52 | "peerDependenciesMeta": { 53 | "gulp": { 54 | "optional": true 55 | } 56 | } 57 | } 58 | -------------------------------------------------------------------------------- /readme.md: -------------------------------------------------------------------------------- 1 | # gulp-nunjucks 2 | 3 | > Compile/precompile [Nunjucks](https://mozilla.github.io/nunjucks/) templates 4 | 5 | *Issues with the output should be reported on the Nunjucks [issue tracker](https://github.com/mozilla/nunjucks/issues).* 6 | 7 | ## Install 8 | 9 | ```sh 10 | npm install --save-dev gulp-nunjucks 11 | ``` 12 | 13 | ## Usage 14 | 15 | ### Compile 16 | 17 | ```js 18 | import gulp from 'gulp'; 19 | import {nunjucksCompile} from 'gulp-nunjucks'; 20 | 21 | export default () => ( 22 | gulp.src('templates/greeting.html') 23 | .pipe(nunjucksCompile({name: 'Sindre'})) 24 | .pipe(gulp.dest('dist')) 25 | ); 26 | ``` 27 | 28 | You can alternatively use [gulp-data](https://github.com/colynb/gulp-data) to inject the data: 29 | 30 | ```js 31 | import gulp from 'gulp'; 32 | import {nunjucksCompile} from 'gulp-nunjucks'; 33 | import data from 'gulp-data'; 34 | 35 | export default () => ( 36 | gulp.src('templates/greeting.html') 37 | .pipe(data(() => ({name: 'Sindre'}))) 38 | .pipe(nunjucksCompile()) 39 | .pipe(gulp.dest('dist')) 40 | ); 41 | ``` 42 | 43 | ### Precompile 44 | 45 | ```js 46 | import gulp from 'gulp'; 47 | import {nunjucksPrecompile} from 'gulp-nunjucks'; 48 | 49 | export default () => ( 50 | gulp.src('templates/greeting.html') 51 | .pipe(nunjucksPrecompile()) 52 | .pipe(gulp.dest('dist')) 53 | ); 54 | ``` 55 | 56 | ## API 57 | 58 | ### nunjucksCompile(data?, options?) 59 | 60 | Compile a template using the provided `data`. 61 | 62 | #### data 63 | 64 | Type: `object` 65 | 66 | The data object used to populate the text. 67 | 68 | #### options 69 | 70 | Type: `object` 71 | 72 | Options will be passed directly to the Nunjucks [Environment constructor](https://mozilla.github.io/nunjucks/api.html#constructor) which will be used to compile templates. 73 | 74 | ##### options.env 75 | 76 | Type: `nunjucks.Environment`\ 77 | Default: `new nunjucks.Environment()` 78 | 79 | The custom Nunjucks [Environment object](https://mozilla.github.io/nunjucks/api.html#environment) which will be used to compile templates. If supplied, the rest of `options` will be ignored. 80 | 81 | ##### options.filters 82 | 83 | Type: `object` 84 | 85 | An object containing [custom filters](https://mozilla.github.io/nunjucks/api.html#custom-filters) that will be passed to Nunjucks, with the filter's name as key and the filter function as value. 86 | 87 | Async filters should be defined as async functions. You cannot use just a promise-returning function. 88 | 89 | ```js 90 | { 91 | 'shorten': string => string.slice(0, 5), 92 | 'round': number => Math.round(number), 93 | 'fetch': async url => { 94 | const response = await fetch(url); 95 | const result = await response.text(); 96 | return result; 97 | } 98 | } 99 | ``` 100 | 101 | ### nunjucksPrecompile(options?) 102 | 103 | Precompile a template for rendering dynamically at a later time. 104 | 105 | Same options as [`nunjucks.precompile()`](https://mozilla.github.io/nunjucks/api.html#precompile) except for `name`. 106 | 107 | #### options 108 | 109 | Type: `object` 110 | 111 | ##### name 112 | 113 | Type: `Function`\ 114 | Default: Relative template path\ 115 | Example: `templates/list.html` 116 | 117 | You can override the default behavior by supplying a function which gets the current [File](https://github.com/gulpjs/vinyl#options) object and is expected to return the name. 118 | 119 | Example: 120 | 121 | ```js 122 | { 123 | name: file => `template-${file.relative}` 124 | } 125 | ``` 126 | -------------------------------------------------------------------------------- /test.js: -------------------------------------------------------------------------------- 1 | import {Buffer} from 'node:buffer'; 2 | import {fileURLToPath} from 'node:url'; 3 | import path from 'node:path'; 4 | import test from 'ava'; 5 | import {pEvent} from 'p-event'; 6 | import data from 'gulp-data'; 7 | import Vinyl from 'vinyl'; 8 | import nunjucksModule from 'nunjucks'; 9 | import {nunjucksCompile, nunjucksPrecompile} from './index.js'; 10 | 11 | const __dirname = path.dirname(fileURLToPath(import.meta.url)); 12 | 13 | test('precompile Nunjucks templates', async t => { 14 | const stream = nunjucksPrecompile(); 15 | const promise = pEvent(stream, 'data'); 16 | 17 | stream.end(new Vinyl({ 18 | base: __dirname, 19 | path: path.join(__dirname, 'fixture', 'fixture.html'), 20 | contents: Buffer.from('

{{ test }}

'), 21 | })); 22 | 23 | const file = await promise; 24 | 25 | t.is(file.path, path.join(__dirname, 'fixture', 'fixture.js')); 26 | t.is(file.relative, path.join('fixture', 'fixture.js')); 27 | t.regex(file.contents.toString(), /nunjucksPrecompiled/); 28 | t.regex(file.contents.toString(), /"fixture\/fixture\.html"/); 29 | }); 30 | 31 | test('compile Nunjucks templates', async t => { 32 | const stream = nunjucksCompile({people: ['foo', 'bar']}); 33 | const promise = pEvent(stream, 'data'); 34 | 35 | stream.end(new Vinyl({ 36 | base: __dirname, 37 | path: path.join(__dirname, 'fixture', 'fixture.njk'), 38 | contents: Buffer.from('{% for name in people %}
  • {{ name }}
  • {% endfor %}'), 39 | })); 40 | 41 | const file = await promise; 42 | 43 | t.is(file.relative, path.join('fixture', 'fixture.html')); 44 | t.is(file.contents.toString(), '
  • foo
  • bar
  • '); 45 | }); 46 | 47 | test('support supplying custom name in a callback', async t => { 48 | const stream = nunjucksPrecompile({ 49 | name: () => 'custom', 50 | }); 51 | 52 | const promise = pEvent(stream, 'data'); 53 | 54 | stream.end(new Vinyl({ 55 | base: __dirname, 56 | path: path.join(__dirname, 'fixture', 'fixture.html'), 57 | contents: Buffer.from('

    {{ test }}

    '), 58 | })); 59 | 60 | const file = await promise; 61 | 62 | t.regex(file.contents.toString(), /{}\)\["custom"]/); 63 | }); 64 | 65 | test('support data via gulp-data', async t => { 66 | const stream = data(file => ({ 67 | dd: file.path, 68 | dt: 'path', 69 | })); 70 | 71 | const finalStream = stream.pipe(nunjucksCompile()); 72 | const promise = finalStream.toArray(); 73 | 74 | stream.write(new Vinyl({ 75 | path: 'foo.txt', 76 | contents: Buffer.from('
    {{ dt }}
    {{ dd }}
    '), 77 | })); 78 | 79 | stream.write(new Vinyl({ 80 | path: 'bar.txt', 81 | contents: Buffer.from('
    {{ dt }}
    {{ dd }}
    '), 82 | })); 83 | 84 | stream.end(); 85 | 86 | const files = await promise; 87 | 88 | t.deepEqual( 89 | files.map(file => file.contents.toString()).sort(), 90 | ['
    path
    bar.txt
    ', '
    path
    foo.txt
    '].sort(), 91 | ); 92 | }); 93 | 94 | test('extend gulp-data and data parameter', async t => { 95 | const stream = data(() => ({ 96 | people: ['foo', 'bar'], 97 | nested: {a: 'one', b: 'two'}, 98 | })); 99 | 100 | const finalStream = stream.pipe(nunjucksCompile({ 101 | heading: 'people', 102 | nested: {a: 'three'}, 103 | })); 104 | 105 | const promise = finalStream.toArray(); 106 | 107 | stream.end(new Vinyl({ 108 | path: 'foo.txt', 109 | contents: Buffer.from('

    {{ heading }}

    {% for name in people %}
  • {{ name }}
  • {% endfor %}{{ nested.a }},{{ nested.b }}'), 110 | })); 111 | 112 | const file = await promise; 113 | 114 | t.is(file[0].contents.toString(), '

    people

  • foo
  • bar
  • one,two'); 115 | }); 116 | 117 | test('not alter gulp-data or data parameter', async t => { 118 | const stream = data(file => ({ 119 | contents: file.contents.toString(), 120 | })); 121 | 122 | const parameter = { 123 | foo: 'foo', 124 | bar: 'bar', 125 | foobar: ['foo', 'bar'], 126 | }; 127 | 128 | const finalStream = stream.pipe(nunjucksCompile(parameter)); 129 | const promise = finalStream.toArray(); 130 | 131 | stream.end(new Vinyl({ 132 | path: 'foo.txt', 133 | contents: Buffer.from('foo'), 134 | })); 135 | 136 | const files = await promise; 137 | 138 | t.deepEqual(files[0].data, {contents: 'foo'}); 139 | 140 | t.deepEqual(parameter, { 141 | foo: 'foo', 142 | bar: 'bar', 143 | foobar: ['foo', 'bar'], 144 | }); 145 | }); 146 | 147 | test('support custom environment', async t => { 148 | const env = new nunjucksModule.Environment(); 149 | 150 | env.addFilter('shorten', x => x.slice(0, 5)); 151 | 152 | const stream = nunjucksCompile({message: 'Lorem ipsum'}, {env}); 153 | const promise = pEvent(stream, 'data'); 154 | 155 | stream.end(new Vinyl({ 156 | path: 'foo.txt', 157 | contents: Buffer.from('{{ message|shorten }}'), 158 | })); 159 | 160 | const file = await promise; 161 | 162 | t.is(file.contents.toString(), 'Lorem'); 163 | }); 164 | 165 | test('support custom environment options', async t => { 166 | const stream = nunjucksCompile({message: 'Lorem ipsum'}, {autoescape: false}); 167 | const promise = pEvent(stream, 'data'); 168 | 169 | stream.end(new Vinyl({ 170 | path: 'foo.txt', 171 | contents: Buffer.from('{{ message }}'), 172 | })); 173 | 174 | const file = await promise; 175 | 176 | t.is(file.contents.toString(), 'Lorem ipsum'); 177 | }); 178 | 179 | test('support custom filters', async t => { 180 | const filters = {shorten: x => x.slice(0, 5), shout: x => `${x}!`}; 181 | const stream = nunjucksCompile({message: 'Lorem ipsum'}, {filters}); 182 | const promise = pEvent(stream, 'data'); 183 | 184 | stream.end(new Vinyl({ 185 | path: 'foo.txt', 186 | contents: Buffer.from('{{ message|shorten|shout }}'), 187 | })); 188 | 189 | const file = await promise; 190 | 191 | t.is(file.contents.toString(), 'Lorem!'); 192 | }); 193 | 194 | test('support async custom filters', async t => { 195 | const filters = {shorten: async x => x.slice(0, 5), shout: async x => `${x}!`}; 196 | const stream = nunjucksCompile({message: 'Lorem ipsum'}, {filters}); 197 | const promise = pEvent(stream, 'data'); 198 | 199 | stream.end(new Vinyl({ 200 | path: 'foo.txt', 201 | contents: Buffer.from('{{ message|shorten|shout }}'), 202 | })); 203 | 204 | const file = await promise; 205 | 206 | t.is(file.contents.toString(), 'Lorem!'); 207 | }); 208 | 209 | test('not pass custom filters to custom environment', async t => { 210 | t.plan(2); 211 | 212 | const env = new nunjucksModule.Environment(); 213 | env.addFilter('shorten', x => x.slice(0, 5)); 214 | const filters = {shout: x => `${x}!`}; 215 | const stream = nunjucksCompile({message: 'Lorem ipsum'}, {env, filters}); 216 | const promise = pEvent(stream); 217 | 218 | stream.end(new Vinyl({ 219 | contents: Buffer.from('{{ message|shorten|shout }}'), 220 | })); 221 | 222 | try { 223 | await promise; 224 | } catch (error) { 225 | t.regex(error.message, /filter not found: shout/); 226 | t.notRegex(error.message, /shorten/); 227 | } 228 | }); 229 | --------------------------------------------------------------------------------