sindresorhus / gulp-nunjucks Goto Github PK
View Code? Open in Web Editor NEWPrecompile Nunjucks templates
License: MIT License
Precompile Nunjucks templates
License: MIT License
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 %}
The example given for precompile
creates the file dist/greeting.html
instead of dist/greeting.js
.
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
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!
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));
});
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.
Would be great if you could allow users to specify custom context for Nunjucks through something like gulp-data.
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.
How can I use this to precompile all files in templates folder into a single templates.js for use in browser?
Currently, when a template extends
a non-existent layout, the plugin throws an error which is long and ugly. It also logs a very large object which looks like the gulp pipeline.
Thanks
The same as options.filters
, but for tags.
The project I'm working requires using the asynchronous templates which causes this plugin to error.
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?
Could we get an upgrade to 2.3+, which has the correct version of nunjucks-slim.js, to work around this?
I could try to do a PR myself.
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 :(
Hello!
Thank you for this great library!
However, how do I specify the base path for templates? The opts
here doesn't have such option.
Thanks!
thanks
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?)
When trying to use {% with %} i get an error message on build... i't ok?
{% with foo = 'bar' %}
{% include 'something.else' %}
{% endwith %}
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
https://mozilla.github.io/nunjucks/api.html#asynchronous-support
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. ๐โโ๏ธ
See the nunjucks docs here, https://mozilla.github.io/nunjucks/api.html#custom-filters
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
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));
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'
}))
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?
A declarative, efficient, and flexible JavaScript library for building user interfaces.
๐ Vue.js is a progressive, incrementally-adoptable JavaScript framework for building UI on the web.
TypeScript is a superset of JavaScript that compiles to clean JavaScript output.
An Open Source Machine Learning Framework for Everyone
The Web framework for perfectionists with deadlines.
A PHP framework for web artisans
Bring data to life with SVG, Canvas and HTML. ๐๐๐
JavaScript (JS) is a lightweight interpreted programming language with first-class functions.
Some thing interesting about web. New door for the world.
A server is a program made to process requests and deliver data to clients.
Machine learning is a way of modeling and interpreting data that allows a piece of software to respond intelligently.
Some thing interesting about visualization, use data art
Some thing interesting about game, make everyone happy.
We are working to build community through open source technology. NB: members must have two-factor auth.
Open source projects and samples from Microsoft.
Google โค๏ธ Open Source for everyone.
Alibaba Open Source for everyone
Data-Driven Documents codes.
China tencent open source team.