Code Monkey home page Code Monkey logo

gulp-nunjucks's Introduction

gulp-nunjucks

Compile/precompile Nunjucks templates

Issues with the output should be reported on the Nunjucks issue tracker.

Install

npm install --save-dev gulp-nunjucks

Usage

Compile

import gulp from 'gulp';
import {nunjucksCompile} from 'gulp-nunjucks';

export default () => (
	gulp.src('templates/greeting.html')
		.pipe(nunjucksCompile({name: 'Sindre'}))
		.pipe(gulp.dest('dist'))
);

You can alternatively use gulp-data to inject the data:

import gulp from 'gulp';
import {nunjucksCompile} from 'gulp-nunjucks';
import data from 'gulp-data';

export default () => (
	gulp.src('templates/greeting.html')
		.pipe(data(() => ({name: 'Sindre'})))
		.pipe(nunjucksCompile())
		.pipe(gulp.dest('dist'))
);

Precompile

import gulp from 'gulp';
import {nunjucksPrecompile} from 'gulp-nunjucks';

export default () => (
	gulp.src('templates/greeting.html')
		.pipe(nunjucksPrecompile())
		.pipe(gulp.dest('dist'))
);

API

nunjucksCompile(data?, options?)

Compile a template using the provided data.

data

Type: object

The data object used to populate the text.

options

Type: object

Options will be passed directly to the Nunjucks Environment constructor which will be used to compile templates.

options.env

Type: nunjucks.Environment
Default: new nunjucks.Environment()

The custom Nunjucks Environment object which will be used to compile templates. If supplied, the rest of options will be ignored.

options.filters

Type: object

An object containing custom filters that will be passed to Nunjucks, with the filter's name as key and the filter function as value.

Async filters should be defined as async functions. You cannot use just a promise-returning function.

{
	'shorten': string => string.slice(0, 5),
	'round': number => Math.round(number),
	'fetch': async url => {
		const response = await fetch(url);
		const result = await response.text();
		return result;
	}
}

nunjucksPrecompile(options?)

Precompile a template for rendering dynamically at a later time.

Same options as nunjucks.precompile() except for name.

options

Type: object

name

Type: Function
Default: Relative template path
Example: templates/list.html

You can override the default behavior by supplying a function which gets the current File object and is expected to return the name.

Example:

{
	name: file => `template-${file.relative}`
}

gulp-nunjucks's People

Contributors

alkorlos avatar bnjmnt4n avatar ingro avatar mohitsinghs avatar ntwb avatar renanvaz avatar richienb avatar shinnn avatar silvenon avatar sindresorhus avatar thedancingcode avatar

Stargazers

 avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar  avatar

Watchers

 avatar  avatar  avatar  avatar  avatar  avatar

gulp-nunjucks's Issues

{% with %}

When trying to use {% with %} i get an error message on build... i't ok?

{% with foo = 'bar' %}
  {% include 'something.else' %}
{% endwith %}

Is it possible to pass the options when using a stream as data?

Like the example you gave:

const gulp = require('gulp');
const nunjucks = require('gulp-nunjucks');
const data = require('gulp-data');

gulp.task('default', () =>
	gulp.src('templates/greeting.html')
		.pipe(data(() => ({name: 'Sindre'})))
		.pipe(nunjucks.compile({
                  watch: true,
                  noCache: true
                }))
		.pipe(gulp.dest('dist'))
);

This one doesn't work. Is there any work around for this?

Add useful stack traces for compilation errors

When an error is thrown by Nunjucks during compilation, no stack trace is given for the source of the error. This makes debugging very difficult.

For example:

> gulp build                                                        

[16:51:38] Using gulpfile ~/Dev/freelance/trizma/gulpfile.js        
[16:51:38] Starting 'build'...                                      
[16:51:38] Finished 'build' after 13 ms                             

events.js:165                                                       
      throw er; // Unhandled 'error' event                          
      ^                                                             
Template render error: TypeError: Cannot read property 'children' of undefined                                                          
    at Object._prettifyError (/home/daniel/Dev/freelance/trizma/node_modules/nunjucks/src/lib.js:35:11)                                 
    at Template.render (/home/daniel/Dev/freelance/trizma/node_modules/nunjucks/src/environment.js:526:21)                              
    at Environment.renderString (/home/daniel/Dev/freelance/trizma/node_modules/nunjucks/src/environment.js:364:17)                     
    at DestroyableTransform._transform (/home/daniel/Dev/freelance/trizma/node_modules/gulp-nunjucks/index.js:25:36)                    
    at DestroyableTransform.Transform._read (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_transform.js:184:10)                                                                                                                                    
    at DestroyableTransform.Transform._write (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_transform.js:172:83)                                                                                                                                   
    at doWrite (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_writable.js:428:64)                          
    at writeOrBuffer (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_writable.js:417:5)                     
    at DestroyableTransform.Writable.write (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_writable.js:334:11)                                                                                                                                      
    at write (/home/daniel/Dev/freelance/trizma/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)      
Emitted 'error' event at:                                           
    at DestroyableTransform.onerror (/home/daniel/Dev/freelance/trizma/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:558:12)                                                                                                                       
    at DestroyableTransform.emit (events.js:180:13)                 
    at DestroyableTransform._transform (/home/daniel/Dev/freelance/trizma/node_modules/gulp-nunjucks/index.js:28:9)                     
    at DestroyableTransform.Transform._read (/home/daniel/Dev/freelance/trizma/node_modules/readable-stream/lib/_stream_transform.js:184:10)                                                                                                                                    
    [... lines matching original stack trace ...]                   
    at write (/home/daniel/Dev/freelance/trizma/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)      
    at flow (/home/daniel/Dev/freelance/trizma/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:632:7)        
npm ERR! code ELIFECYCLE                                            
npm ERR! errno 1                                                    
npm ERR! @ build: `gulp build`                                      
npm ERR! Exit status 1                                              
npm ERR!                                                            
npm ERR! Failed at the @ build script.                              
npm ERR! This is probably not a problem with npm. There is likely additional logging output above.                                      

npm ERR! A complete log of this run can be found in:                
npm ERR!     /home/daniel/.npm/_logs/2018-04-10T07_21_38_514Z-debug.log        

Here's the task for my Nunjucks templates:

const templates = () => gulp
  .src(paths.templates.src)
  .pipe(nunjucks.compile())
  .pipe(rename({
    dirname: '.',
    extname: '.html',
  }))
  .pipe(prettify())
  .pipe(gulp.dest(paths.templates.dest));

Error Handling

Hey, I can't seem to get error handling to work. I spent about half an hour trying to play around with the source, it seems that it should be changed to something like

                 try {
			const content = env.renderString(file.contents.toString());
			console.log(content);
			if(content) {
				file.contents = new Buffer(content, context);
			} else {
				throw new Error("Invalid file");	
			};
			this.push(file);
			
		} catch (err) {

because env.renderString returns 'null' if an error occurs. In your code when you go to add that "buffer" to the file.contents it errors.

I'm also not sure how to catch and handle errors on my end. I have this:

		.pipe(nunjucks.compile({
				path: ['./src/html', './src'],
			})).on('error', function(err) {
				console.log('\x1b[31m', 'nunjucksRender error: ', err.message, '\x1b[0m');
				this.emit('end');
			})

I also tried making the .on('error') portion attach to the nunjucks.compile function rather than the pipe and still had no success.

Any help appreciated!

Typos in readme API after update to 6.0.0

Now in readme.md

nunjucks.compile(data?, options?)

and

nunjucks.precompile(options?)

In v6.0.0 have change:

Switched to named imports

The example needs to be corrected to

nunjucksCompile(data?, options?)

and

nunjucksPrecompile(options?)

Wrong file name in output when multiple templates are processed

Hello, first of all thanks for this and your other plugins for Gulp!

Anyway I found an issue while working with multiple templates, here's an example code:

gulp.task('templates', function() {
    gulp.src(['public/templates/**/*.html'])
    .pipe(nunjucks())
    .pipe(concat('templates.js'))
    .pipe(gulp.dest('public/scripts/build'));
});

If for example I have this templates in my target folder:

posts/
->list.html
->single.html
admin.html
main.html

in the output javascript file they are all present but all named as 'admin.html' and so not usable in the browser.

Looking at the source code I suppose it assign the first file's path to the name attribute in the option hash and so all the subsequent templates will have the same name, since they share the same option variable.

I hope that I managed to explain the problem well enough, sorry for my bad english :(

Indentation bug

If head and body tags are not indented then output html is fine, but if they are not indented output html is ugly. Try to use blocks and template extension

First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

Hey,
I have a problem while compiling my project.

Infos:
package.json

 {
  "name": "node",
  "version": "1.0.0",
  "description": "",
  "main": "index.js",
  "scripts": {
    "test": "echo \"Error: no test specified\" && exit 1",
    "replacer": "node replacer.js",
    "gulp": "gulp"
  },
  "author": "me",
  "license": "MIT",
  "devDependencies": {
    "browser-sync": "^2.18.13",
    "csslint": "^1.0.5",
    "gulp": "^3.9.1",
    "gulp-clean-css": "^3.10.0",
    "gulp-cli": "^1.3.0",
    "gulp-csslint": "^1.0.1",
    "gulp-less": "^3.3.2",
    "gulp-nunjucks": "^4.0.0",
    "gulp-nunjucks-render": "^2.2.2",
    "gulp-rename": "^1.2.2",
    "gulp-sass": "^4.0.2",
    "gulp-util": "^3.0.8",
    "node-sass": "^4.11.0",
    "nunjucks": "^3.1.7",
    "stream-combiner2": "^1.1.1"
  }
}

my gulpfile:

// Include gulp
var gulp = require('gulp');

// Include Our Plugins
var sass = require('gulp-sass');
var browserSync = require('browser-sync');
var reload      = browserSync.reload;
var util = require('gulp-util');
var cleanCSS = require('gulp-clean-css');
var rename = require('gulp-rename');
var nunjucks = require('gulp-nunjucks');
var cleanCSS = require('gulp-clean-css');
var csslint = require('gulp-csslint');

var cssLintConfig = {<lint config>}
// lint css
gulp.task('csslint', function() {<some code here>});

// Compile Our css
gulp.task('sass', function() {<some code here>});
// browser-sync
gulp.task('browser-sync', function () {<some code here>});

gulp.task('nunjucks', () =>
    gulp.src('pages/base.html')
        .pipe(nunjucks.compile().on('error', function(error){
            console.log(error);
        }))
        .pipe(gulp.dest('public'))
          .pipe(reload({stream: true}))
);

// Watch Files For Changes
gulp.task('watch', function() {<some code here>});

gulp.task('minify-css', () => {<some code here>});

// Default Task
gulp.task('default', ['nunjucks', 'sass', 'watch', 'browser-sync']);

the error stack:

[07:30:46] Starting 'nunjucks'...
[07:30:47] { TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
    at Function.Buffer.from (buffer.js:183:11)
    at DestroyableTransform._transform (<root>/node_modules/gulp-nunjucks/index.js:29:27)
    at DestroyableTransform.Transform._read (<root>/node_modules/readable-stream/lib/_stream_transform.js:184:10)
    at DestroyableTransform.Transform._write (<root>/node_modules/readable-stream/lib/_stream_transform.js:172:83)
    at doWrite (<root>/node_modules/readable-stream/lib/_stream_writable.js:428:64)
    at writeOrBuffer (<root>/node_modules/readable-stream/lib/_stream_writable.js:417:5)
    at DestroyableTransform.Writable.write (<root>/node_modules/readable-stream/lib/_stream_writable.js:334:11)
    at write (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)
    at flow (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:632:7)
    at DestroyableTransform.pipeOnReadable (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:664:5)
  message: 'First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.',
  name: 'TypeError',
  stack: 'TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.\n    at Function.Buffer.from (buffer.js:183:11)\n    at DestroyableTransform._transform (<root>/node_modules/gulp-nunjucks/index.js:29:27)\n    at DestroyableTransform.Transform._read (<root>/node_modules/readable-stream/lib/_stream_transform.js:184:10)\n    at DestroyableTransform.Transform._write (<root>/node_modules/readable-stream/lib/_stream_transform.js:172:83)\n    at doWrite (<root>/node_modules/readable-stream/lib/_stream_writable.js:428:64)\n    at writeOrBuffer (<root>/node_modules/readable-stream/lib/_stream_writable.js:417:5)\n    at DestroyableTransform.Writable.write (<root>/node_modules/readable-stream/lib/_stream_writable.js:334:11)\n    at write (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:623:24)\n    at flow (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:632:7)\n    at DestroyableTransform.pipeOnReadable (<root>/node_modules/vinyl-fs/node_modules/readable-stream/lib/_stream_readable.js:664:5)',
  __safety: undefined,
  _stack: undefined,
  plugin: 'gulp-nunjucks',
  showProperties: true,
  showStack: false,
  fileName: '<root>/pages/base.html' }

it seems to happen when files get too big. Are there any known problems?
I have created a nunjucks vanilla build and it runs fine:

// Nunjucks
fs = require('fs');
nunjucks = require('nunjucks');

nunjucks.render('./pages/base.html',function(err, res) {
    //console.log(res);
    fs.writeFile('test.html', res, function(err) {
        if (err) throw err;
    });  
    console.log("---");
    console.log("Error " + err); // returns null
});

any ideas how to solve the error above? Or is there maybe a misconfig?

Is this plugin compatible with nunjucks-markdown?

I'm trying to use gulp-nunjucks with nunjucks markdown and I'm getting a weird result. The plugin inserts the string undefined wherever I have the markdown tag, but it works fine with HTML. Is there an example of this plugin working with nunjucks-markdown? I haven't found any and I'm curious if I did it right.

Here is the entire code I'm using as a Gulp task, in case someone can spot any errors.

// Require Gulp first
const gulp = require('gulp');
const extReplace = require('gulp-ext-replace');

// Nunjucks and Markdown
const nunjucks = require('nunjucks');
const markdown = require('nunjucks-markdown');
const gulpnunjucks = require('gulp-nunjucks');
// const nunjucksRender = require('gulp-nunjucks-render');
const grayMatter = require('gulp-gray-matter');
const MarkdownIt = require('markdown-it');
const md = require('markdown-it')();

// Nunjucks consts for file location
const dist = 'docs';
const src = 'src';
const templates = src + '/templates';
const content = src + '/pages';

// Where to pull files from?
const env = new nunjucks.Environment(new nunjucks.FileSystemLoader(templates));

markdown.register(env, (text) => {
  md.render(text);
});

gulp.task('renderContent', function() {
  return gulp.src(content + '/**/*.md')
      .pipe(grayMatter())
      .pipe(gulpnunjucks.compile('', {env: env}))
      .pipe(extReplace('.html'))
      .pipe(gulp.dest(dist));
});

Configure

Hi Sindresorhus,

Trying to use your gulp plugin but not sure how to pass through options that go into nunjucks.configure() ?

Another silly question, is there away I can avoid using relative paths for my includes?
instead of: " ../../component/componentName/fileName.nunjucks "
I want: " componentName/fileName.nunjucks "

Thanks

TypeError: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.

Hello! I'm trying to use gulp-nunjucks to compile Twig syntax in PatternLab Node Gulp edition.

I keep getting the following error, and I'm not sure how to resolve it:

TypeError in plugin 'gulp-nunjucks'
Message: First argument must be a string, Buffer, ArrayBuffer, Array, or array-like object.
Details:
    fileName: // first .twig file in my gulp.src
    domainEmitter: [object Object]
    domain: [object Object]
    domainThrown: false

Here's the relevant part of my gulpfile.js:

const nunjucks_gulp = require('gulp-nunjucks');
const nunjucks_lib = require('nunjucks');

gulp.task('nunjucks', () =>
  gulp.src(normalizePath(paths().source.templates + '**/*.twig'))
   .pipe(nunjucks_gulp.compile(
      {},
      {env: new nunjucks_lib.Environment(new nunjucks_lib.FileSystemLoader(normalizePath(paths().source.patterns)))}
    ))
    .pipe(gulp.dest(normalizePath(paths().public.templates)))
);

I understand that compile takes two arguments, data and options. It seems like I have two arguments there, {} and my env option.

My end goal is to get html files in my public.templates directory, so maybe there is a function I could use besides compile? I'm open. If I replace compile with precompile and remove the first argument, gulp nunjucks completes with no errors, but it doesn't seem like it actually does anything.

Please help me figure out what I'm missing! Thank you in advance. ๐Ÿ™‡โ€โ™€๏ธ

Possible to specify extension for output?

I like to use the .njk extension to specify a template file. This plugin seems to pass that extension through as the output name. Is there a way to force it to output as .html without using other plugins?

If not maybe a good feature enhancement as I can't think of a scenario where one would want to output something besides an .html file.

Undefined value of template function argument

Hello,

I've decided to report this issue here, not in nunjucks repository, mainly because the problem occured after I've upgraded gulp-nunjucks to 2.1.1, regardless of the version of nunjucks.

As the title says, when I'm invoking function with argument within template, the value of the argument is undefined. It works when I'm using [email protected]. I haven't tried anything between these two versions.

My first thought was to try switch nunjucks version, unfortunately with no effect.
Only downgrading gulp-nunjucks version helped.

Nunjucks Incompatibility runtime.fromIterator Error

Recently I have been getting the error TypeError: runtime.fromIterator is not a function whenever I try using a precompiled template with a for statement. I figured out that the issue is related to nunjucks version as described in this post on the nunjucks github page mozilla/nunjucks#1091

I have been able to fix the issue by forcing npm to install nunjucks 3.0.x as described in the url above. It would be awesome if gulp-nunjucks were updated to the current 3.1.x.

Thanks

Using absolute url in include

How to use absolute url in includes like this {% include '/testBlock/testBlock.html' %}?
How to set a base folder for absolute paths?

Gulp-jade, for example, had option basedir:

    .pipe(jade({
        basedir: 'assets'
    }))

Template not found when I using extends in my template

This is my project tree view:

src
`-- templates
    |-- _layouts
    |   `-- login.layout.njk
    `-- pages
        `-- login.njk

And the login.njk

{% extends "../_layouts/login.layout.njk" %}
{% block main_content %}
  login page!
{% endblock %}

Recommend Projects

  • React photo React

    A declarative, efficient, and flexible JavaScript library for building user interfaces.

  • Vue.js photo Vue.js

    ๐Ÿ–– Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.

  • Typescript photo Typescript

    TypeScript is a superset of JavaScript that compiles to clean JavaScript output.

  • TensorFlow photo TensorFlow

    An Open Source Machine Learning Framework for Everyone

  • Django photo Django

    The Web framework for perfectionists with deadlines.

  • D3 photo D3

    Bring data to life with SVG, Canvas and HTML. ๐Ÿ“Š๐Ÿ“ˆ๐ŸŽ‰

Recommend Topics

  • javascript

    JavaScript (JS) is a lightweight interpreted programming language with first-class functions.

  • web

    Some thing interesting about web. New door for the world.

  • server

    A server is a program made to process requests and deliver data to clients.

  • Machine learning

    Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.

  • Game

    Some thing interesting about game, make everyone happy.

Recommend Org

  • Facebook photo Facebook

    We are working to build community through open source technology. NB: members must have two-factor auth.

  • Microsoft photo Microsoft

    Open source projects and samples from Microsoft.

  • Google photo Google

    Google โค๏ธ Open Source for everyone.

  • D3 photo D3

    Data-Driven Documents codes.