Nunjucks throws this error when I am restarting GULP. I cannot see what the problem might be. Unfortunately Nunjucks does not give me the file or tag where this is happening.
events.js:141
throw er; // Unhandled 'error' event
^
Template render error: (unknown path)
Template render error: expected block end in endblock statement
at Object.exports.withPrettyErrors (D:devngs-frontend-nextnode_modulesgulp-nunjucks-rendernode_modulesnunjuckssrclib.js:35:17)
at Obj.extend.render (D:devngs-frontend-nextnode_modulesgulp-nunjucks-rendernode_modulesnunjuckssrcenvironment.js:374:20)
at Obj.extend.renderString (D:devngs-frontend-nextnode_modulesgulp-nunjucks-rendernode_modulesnunjuckssrcenvironment.js:261:21)
at Object.module.exports.renderString (D:devngs-frontend-nextnode_modulesgulp-nunjucks-rendernode_modulesnunjucksindex.js:66:14)
at Transform._transform (D:devngs-frontend-nextnode_modulesgulp-nunjucks-renderindex.js:46:21)
It seems like I have the block and enblock correctly defined in my base index.html file. I have these two tags :
{% block content %}
…..
{% endblock include "components/cmpBreadcrumb/cmpBreadcrumb.html" %}
Any ideas?
asked Dec 23, 2015 at 10:35
Oliver WatkinsOliver Watkins
11.8k26 gold badges112 silver badges213 bronze badges
Is there a reason you are including within the endblock? I can repeat the same error you had by coupling the include
and endblock
together in the same tag.
From what I’ve read unless you are using a filter or something else naturally done together in a block they should be broken out into their own tags.
If you want the include that file in the content it should be before the close,
{% block content %}
[...]
{% include "components/cmpBreadcrumb/cmpBreadcrumb.html" %}
{% endblock %}
answered Dec 23, 2015 at 22:55
1
не создаётся index.html в корневом каталоге уже 5 раз перепробовал результат тот же вот данные
gulpfile.js
const { src, dest, watch, parallel, series } = require('gulp');
const scss = require("gulp-sass")(require("sass"));
const concat = require("gulp-concat");
const autoprefixer = require("gulp-autoprefixer");
const uglify = require("gulp-uglify");
const imagemin = require("gulp-imagemin");
const nunjucksRender = require("gulp-nunjucks-render");
const del = require("del");
const { reload } = require('browser-sync');
const browserSync = require("browser-sync").create();
function nunjucks() {
return src("app/*.njk")
.pipe(nunjucksRender())
.pipe(dest("app"))
.pipe(browserSync.stream());
}
function browsersync(params) {
browserSync.init({
server:{
baseDiu:'app/'
},
notify:false
})
}
function styles() {
return src("app/scss/style.scss")
.pipe(scss({ outputStyle: "compressed" }))
.pipe(concat("style.min.css"))
.pipe(
autoprefixer({
overrideBrowserslist: ["last 10 versions"],
grid: true,
})
)
.pipe(dest("app/css"))
.pipe(browserSync.stream());
}
function scripts() {
return src([
"node_modules/jquery/dist/jquery.js",
"node_modules/slick-carousel/slick/slick.js",
"node_modules/@fancyapps/fancybox/dist/jquery.fancybox.js",
"node_modules/rateyo/src/jquery.rateyo.js",
"node_modules/ion-rangeslider/js/ion.rangeSlider.js",
"node_modules/jquery-form-styler/dist/jquery.formstyler.js",
"app/js/main.js",
])
.pipe(concat("main.min.js"))
.pipe(uglify())
.pipe(dest("app/js"))
.pipe(browserSync.stream());
}
function images() {
return src("app/images/**/*.*")
.pipe(
imagemin([
imagemin.gifsicle({ interlaced: true }),
imagemin.mozjpeg({ quality: 75, progressive: true }),
imagemin.optipng({ optimizationLevel: 5 }),
imagemin.svgo({
plugins: [{ removeViewBox: true }, { cleanupIDs: false }],
}),
])
)
.pipe(dest("dist/images"));
}
function build() {
return src([
'app/**/*.html',
'app/css/style.min.css',
'app/js/main.min.js',
], {base:'app'})
.pipe(dest('dist'))
}
function cleanDist(params) {
return del('dist')
}
function watching() {
watch(["app/scss/**/*.scss"], styles);
watch(["app/*.njk"], nunjucks);
watch(['app/js/**/*.js','!app/js/main.min.js'], scripts);
watch(['*.html']).on('change',browserSync.reload);
}
exports.styles = styles;
exports.scripts = scripts;
exports.browsersync = browsersync;
exports.watching = watching;
exports.images = images;
exports.nunjucks = nunjucks;
exports.cleanDist = cleanDist;
exports.build = series(cleanDist, images, build);
exports.default = parallel(nunjucks, styles, scripts, browsersync, watching);
package.json
{
"name": "gulp-start",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo "Error: no test specified" && exit 1"
},
"author": "dj",
"license": "ISC",
"devDependencies": {
"@fancyapps/fancybox": "^3.5.7",
"del": "^6.0.0",
"gulp": "^4.0.2",
"gulp-autoprefixer": "^8.0.0",
"gulp-concat": "^2.6.1",
"gulp-imagemin": "^7.1.0",
"gulp-nunjucks-render": "^2.2.3",
"gulp-sass": "^5.0.0",
"ion-rangeslider": "^2.3.1",
"rateyo": "^2.3.2",
"sass": "^1.44.0",
"slick-carousel": "^1.8.1"
},
"dependencies": {
"@fancyapps/ui": "^4.0.11",
"browser-sync": "^2.27.7",
"gulp-uglify": "^3.0.2",
"jquery": "^3.6.0",
"jquery-form-styler": "^2.0.2"
}
}
какие еще данные нужны?
встало обучение 3 день не могу решить где ошибка.
carlitoplatanito / gulp-nunjucks-render
Goto Github
PK
View Code? Open in Web Editor
NEW
10.0
31.0
111 KB
[Gulp](https://github.com/wearefractal/gulp) plugin to render [Nunjucks](http://mozilla.github.io/nunjucks/) templates
JavaScript 92.83%
HTML 5.83%
Smarty 1.34%
gulp-nunjucks-render’s Introduction
Render Nunjucks templates
Issues with the output should be reported on the Nunjucks issue tracker.
Install
Install with npm
npm install --save-dev gulp-nunjucks-render
Example
var gulp = require('gulp'); var nunjucksRender = require('gulp-nunjucks-render'); gulp.task('default', function () { return gulp.src('src/templates/*.html') .pipe(nunjucksRender({ path: ['src/templates/'] // String or Array })) .pipe(gulp.dest('dist')); });
Example with gulp data
var gulp = require('gulp'); var nunjucksRender = require('gulp-nunjucks-render'); var data = require('gulp-data'); function getDataForFile(file) { return { example: 'data loaded for ' + file.relative }; } gulp.task('default', function () { return gulp.src('src/templates/*.html') .pipe(data(getDataForFile)) .pipe(nunjucksRender({ path: 'src/templates' })) .pipe(gulp.dest('dist')); });
API
Options
Plugin accepts options object, which contain these by default:
var defaults = { path: '.', ext: '.html', data: {}, inheritExtension: false, envOptions: { watch: false }, manageEnv: null, loaders: null };
path
— Relative path to templatesext
— Extension for compiled templates, pass null or empty string if yo don’t want any extensiondata
— Data passed to templateinheritExtension
— If true, uses same extension that is used for templateenvOptions
— These are options provided for nunjucks Environment. More info here.manageEnv
— Hook for managing environment before compilation. Useful for adding custom filters, globals, etc. Example belowloaders
— If provided, uses that as first parameter to Environment constructor. Otherwise, uses providedpath
. More info here
For more info about nunjucks functionality, check https://mozilla.github.io/nunjucks/api.html and also a source code of this plugin.
Data
U can pass data as option, or you can use gulp-data like in example above.
nunjucksRender({data: { css_path: 'http://company.com/css/' }});
For the following template
<link rel="stylesheet" href="{{ css_path }}test.css" />
Would render
<link rel="stylesheet" href="http://company.com/css/test.css" />
Environment
If you want to manage environment (add custom filters or globals), you can to that with manageEnv
function hook:
var manageEnvironment = function(environment) { environment.addFilter('slug', function(str) { return str && str.replace(/s/g, '-', str).toLowerCase(); }); environment.addGlobal('globalTitle', 'My global title') } nunjucksRender({ manageEnv: manageEnvironment }):
After adding that, you can use them in template like this:
<h1>{{ globalTitle }}</h1> <h3>{{ 'My important post'|slug }}</h3>
And get this result:
<h1>My global title</h1> <h3>my-important-post</h3>
License
MIT © Carlos G. Limardo and Kristijan Husak
Shout-outs
Sindre Sorhus who wrote the original gulp-nunjucks for precompiling Nunjucks templates. I updated his to render instead of precompile.
kristijanhusak for bug fixes and help with maintenance.
gulp-nunjucks-render’s People
gulp-nunjucks-render’s Issues
Empty .ext is defaulting to .html if options.ext = »
If I want to pass in an extension of nothing the plugin will default to .html. Sometimes it will be desired for us to pass in no extension as our template might be titled as «index.html.nunjucks»
We could change line 12
if(!options.ext)
to if(options.ext === undefined)
which will allow to pass in no extension
How to pass Vinyl file data to templates?
How does one pass Vinyl file objects to the templates?
// layout.nunjucks {{file.path}} {{file.dirname}} {{file.relative}}
When building navigation menus, internationalising pages and doing SEO, I’ve often found myself in need for the page to know it’s own path. How to do it? I’ve been breaking my head over this, but can’t figure it out.
The closest I’ve come is to use Gulp Tap which outputs file data, but I haven’t been able to pass this as data to nunjucksrender
.
gulp.task('compileHtml', () => {
return gulp.src(`src/templates/pages/**/*.+(html|nunjucks)`)
.pipe(tap(function(file, t) {
util.log(file.dirname.toString())
}))
.pipe(nunjucksRender({
path: ['src/templates'],
data: {
data: myData
}
}))
.pipe(gulp.dest(`dist/`))
});
Any ideas?
Template render error — should empty the stream
When ever a Template render error occurs, the rendering stops, but the remaining input files stay unchanged in the stream and end up being written (with their original filenames) into the dest folder.
This results in crap building up in the output folder.
Shouldn’t the renderer empty the stream on error?
Update npm release
Is it possible to add custom tags?
Update for nunjucks 3.0.0
nunjucks 3.0.0 was released, any chance you can update this plugin to make it use the new version? Thanks!
how to disable auto escaping?
tried
.pipe($.nunjucksRender({
path: 'app',
autoescape: false
}))
but didn’t work
Add info to docs
Hey,
in every nunjucks template you add a magic variable name that is filename the is being processed.
I think you should add it to docs page
Gulp freezes upon completion with basic usage
Is this usage error or have I found a bug?
Output:
$ gulp update-version
[07:18:10] Using gulpfile C:gitquick-testgulpfile.js
[07:18:10] Starting 'update-version'...
[07:18:10] Finished 'update-version' after 69 ms
<<< frozen, not returned to command prompt
Gulp file:
var gulp = require('gulp'); var data = require('gulp-data'); var nunjucksRender = require('gulp-nunjucks-render'); var rename = require('gulp-rename'); var gutil = require('gulp-util'); function getVersion() { return { 'version': 'quick-test-123' }; } gulp.task('update-version', function() { nunjucksRender.nunjucks.configure([ 'Source/Shared/' ]); return gulp.src('Source/Shared/GlobalAssemblyInfo.cs.nj') .pipe(data(getVersion())) .pipe(nunjucksRender()) .pipe(rename('GlobalAssemblyInfo.cs')) .pipe(gulp.dest('Source/Shared/')) ; });
Versions:
"node": "0.12.3",
"gulp": "^3.8.11",
"gulp-data": "^1.2.0",
"gulp-nunjucks-render": "^0.2.1",
"gulp-rename": "^1.2.2",
"gulp-util": "^3.0.4",
Many thanks!
How to manage tags configuration?
I try to change default tags:
gulp.task(‘default’, function () {
return gulp.src(‘src/templates/*.html’)
.pipe(nunjucksRender({
tags: {
blockStart: ‘<%’,
blockEnd: ‘%>’,
variableStart: ‘<$’,
variableEnd: ‘$>’,
commentStart: ‘<#’,
commentEnd: ‘#>’
},
path: [‘src/templates/’] // String or Array
}))
.pipe(gulp.dest(‘dist’));
});
it doesn’t work
thanks
2.2.3 release
72fccab bumped the version to 2.2.3, but no Github release was cut. I believe only maintainers can add tags (Github doesn’t have a way to PR tags does it?). Would be great to add the 2.2.3
tag
{% with %} error
When i trying to use {% with %} i received an error message on build…
{% with foo = 'bar' %}
{% include 'something.else' %}
{% endwith %}
Filtering partials with watch in Gulp
In my views
folder, I have a folders that start with _
that contain partials, that I’m filtering out from rendering:
var views = path.join(config.paths.src, 'views');
var src = [
path.join(views, '**/*.html'),
'!' + path.join(views, '_*/*'),
];
nunjucksRender.nunjucks.configure(
[views],
{ watch: false }
);
gulp.task('build:html:render', function() {
return gulp.src(src)
.pipe(nunjucksRender())
.pipe(gulp.dest(dest));
});
This works great with one exception: When I run this task from gulp.watch
, it only runs when I save one of my non-underscored files, but I want it to re-render everything on any save with views
.
gulp.watch([
path.join(config.paths.src, 'views/**/*.html'),
], gulp.series(
'build:html:render'
));
Any ideas?
How to disable {{}}
Vue and gulp-nunjucks-render have conflicts, I want to disable {{}}, but I don’t know what to do
OAQ
Can’t import v2.2.0
Hi, I can’t import latest version.
[15:40:24] Error: Cannot find module 'gulp-nunjucks-render' from 'my-home-project'
Template not found.
Hello,
I’ve adding some errors that i don’t understand, because the path is right.
Template render error in plugin ‘gulp-nunjucks’
(unknown path)
Error: template not found: layout.njk
gulp file:
nunjucksRender.nunjucks.configure(['_src/templates/']);
// Gets .html and .nunjucks files in pages
return gulp.src('_src/pages/**/*.+(html|nunjucks|njk)')
And the files are there:
_src
—templates
—layout.njk
Thank you
Maintaned?
Is this plugin maintained?
Bump nunjucks requirement to 1.2.0
Nunjucks recently updated to 1.2.0, which added some fun stuff.
No tests to see if this would break anything, but it’d be awesome to get it in!
missing index.js in npm package of v2.1.0
Hi,
after an update to v2.1.0 there is no more «index.js», so require() is broken.
Please fix, thanks!
Templating relative path
Is it possible to set path to {% extends parent.html %}
via path relative to child.html?
Currently it’s relative to project root.
E.g. something like this
{% extends layout/parent.html %}
and not
{% ./app/views/layout/parent.html %}
Customizing Syntax
Hi, Can you help me?
how to set up the syntax changes
var render = require('gulp-nunjucks-render')
render.nunjucks.configure(config.nunjucks, {
watch: false ,
tags: {
variableStart: '<$',
variableEnd: '$>'
}
})
This to does not work
Thanks
Example using extensions e.g. https://www.npmjs.com/package/nunjucks-i18n
When attempting to add this extension to the environment the block tag i18n resulted in this error:
[13:27:24] gulp-notify: [Error running Gulp] Template render error in plugin 'gulp-nunjucks'
(unknown path) [Line 11, Column 2]
unknown block tag:
i18n
URL structure
Is it possible to customize the URL and output structure of the pages so that instead of url.com/about.html
would be url.com/about/
(which is obviously url.com/about/index.html
)?
I’m wondering if this is the ext:
option, but I haven’t found any examples as to how this would be possible.
If I need to ask this somewhere else, let me know. Thanks!
reloading for each template with browsersync
Hi,
I have a front-end workflow with Nunjucks template, SASS and Browsersync.
For some time, the compilation of Nunjucks bug with Browsersync. Before when I ran Gulp, Browsersync reloaded one time the Nunjcuks files. Now Browsersync reload as many time as there are Nunjucks files.
I notice that there were changes with version of Lodash library, can that come from that?
My Nunjucks task :
var siteRoot = './'; var siteSources = 'sources_fe/'; var render = siteRoot + 'render/'; var templatesFolder = siteSources + 'templates/'; var templatesInput = templatesFolder + '**/*.njk'; gulp.task('njk', function () { return gulp.src(templatesInput) .pipe(nunjucksRender({ path: templatesFolder, ext: '.html' })) .pipe(gulp.dest(render)) .pipe(reload({stream: true})); });
Thank you for your help.
Small Changes Not Compiled
Have a weird problem with nunjucks. When I make small changes to a comment section in a parent template, the ‘page’ template that extends the parent, does not get compiled (although the file to be compiled is being passed to nunjucks). If I type an extra word or two in the source parent template, all works as expected. I suspect this is a nunjucks problem, and not gulp-nunjucks-render — but thought I’d post here as well just in case I’m missing something obvious.
Here’s the issue I’ve posted with nunjucks… mozilla/nunjucks#810
Problem when using with nunjucks-markdown
I’m trying to use this plugin together with Markdown-it, Graymatter. and nunjucks-markdown. For some reason the renderer is not recognizing the {% markdown %}
tag.
The error I’m getting:
[08:03:43] Template render error in plugin "gulp-nunjucks" Message: (unknown path) [Line 3, Column 4] unknown block tag: markdown Details: fileName: /Users/carlos/code/static-gen-njk/src/pages/css-containment.md domainEmitter: [object Object] domainThrown: false
Are there examples of using the plugin with markdown parsers other than Marked? How do you fix this issue?
Strange problem when using with gulp-useref
I have a workflow where one gulp task compiles nunjucks templates (with the help of this plugin) and outputs them to temporary folder and then other task uses gulp-useref to replace build blocks (for example I have css build block that must be replaced with combined and minified css file).
The problem is useref doesn’t do it’s job, but it’s not useref problem. Everything is working fine with plain html files, but after this plugin renders html, useref is not doing its’ job. The most strange thing is that when I manually open .html
file in temporary folder, delete newline before build block (there’s a newline there) and add it again (simply pressing enter) and run the useref task again, it does it’s job. There is a feeling that there’s some problem with newline, or there’s a hidden character there….
How to handle error?
Here is my code.
gulp.task('nunjucks', function () {
return gulp.src('html/pages/**/*.+(html|nunjucks)')
.pipe($.nunjucksRender({
path: ['html/templates']
}))
.pipe(gulp.dest('dist'));
});
Outdated dependencies and some desired features
I am creating this issue for a few reasons
1. All dependencies are outdated.
I tested it with latest dependencies and all tests were successfully passed.
2. The default data option requires object type.
The default data option requires an object. We can instead check for whether an object or a path string is passed. In the case of data object it will be merge to default data while in the case of path it should first parse json and then merge parsed data with default data.
3. Handle template inheritance and markdown.
This could be treated as a feature request and can be avoided if needed .
If a file with front-matter is triggered and it contains a layout
object then it should be handled differently. The front-matter should be merged with default data as something like page
object so that front-matter data could be accessed in parent templates using {{ page.title }}
etc.
Further the body contents should be wrapped with extends
and block
tags so that we can get layout from front-matter and render current file with desired layout file. Also If current file is markdown that we should parse it with marked before rendering.
According to Nunjucks Changelog, starting from 3.0.0 released on Nov 5,
base templates can no longer see vars set in templates that inherit them.
Hence parsing data objects from front-matter and merging it with data passed before rendering template will allow using that data in parent templates.
I have created PR #56 with suggested changes.
If there is something I missed, please correct me. Thanks in advance.
can we use globbing for path?
like this src/pages/**/partials
?
Gulp data support
Hello.
Any chance to see gulp-data support?
Nunjucks-render won’t build on windows
Hello,
I have a project that uses your npm package and it runs fine on linux, but it hangs on Windows. Both Windows 10 (my local machine) and our Jenkins servers (Windows Server 2013).
Windows 10:
node -v | v10.16.0
npm -v | 6.9.0
I’m using gulp and here is my nunjucksrender() function:
.pipe( nunjucksRender( { path: './demo/nunjucks/', // Relative path to templates ext: '.html', //Extension for compiled templates data: { //Data passed to template cdc_path: 'https://cdc.gov/', }, inheritExtension: false, //If true, uses same extension that is used for template envOptions: { //These are options provided for nunjucks Environment. watch: false }, manageEnv: manageEnvironment, //Hook for managing environment before compilation. loaders: null //If provided, uses that as first parameter to Environment constructor. } ) ) //nunjucks render
I’ve tried removing all options, just adding in the path, etc. etc.
I’ve confirmed on multiple machines both linux and windows the same behavior. It works on linux and mac but not on windows.
It literally just sits there in gitbash and hangs, taking up CPU usage without ever finishing.
Just trying to give you the right information to help troubleshoot. I’ve been researching for days, please tell me if I’m missing something.
Thanks
- Jim
Upgrade to nunjucks 1.3.0
How to include a macro in another file?
I have three file structures like:
_skeleton-content.html
<div class="page-content"></div>
{% block include_footer %}
{% endblock %}
_macros.html
{% macro script(files) %}
{% for file in files %}
<script type="text/javascript" src="{{ file }}"></script>
{% endfor %}
{% endmacro %}
index.html
{% extends "sections/_skeleton-content.html" %}
{% include "sections/_macros.html" %}
{% block include_footer %}
{{ script(['jquery.js','home.js']) }}
{% endblock %}
But this isn’t working. The error is
unable to call script which is undefined or falsey
npm published version (2.2.2) depends on vulnerable lodash version
This seems to have been fixed in #67 but not tagged for release and published to npm. Due to CVE-2018-3721, please consider republishing this package with the updated lodash.
Default keyword arguments don’t work on macros
According to documentation here and here, you can set the defaults within macros:
{% macro field(name, value='', type='text') %}
I discovered that default values don’t work on gulp-nunjucks-renderer
: when I set them, I get blank values. In the example snippet above, I’d be getting empty value
, even if non-empty variable were being passed into it.
Can anybody confirm please, do you see this happening?
cheers
Error building html with subfolder
In my project I need the following file structure:
webapp
└── app
├── index.html
├── subfolder
│ ├── index.html
├── includes
│ ├── footer.html
│ └── header.html
└── layouts
└── default.html
When I build the HTML, the following error occurs:
events.js:154
throw er; // Unhandled 'error' event
^
Error: Error: File not found with singular glob: /Users/macweb01/Sites/ccr/ras/styles/main.css
at DestroyableTransform.<anonymous> (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/lib/streamManager.js:90:36)
at emitOne (events.js:95:20)
at DestroyableTransform.emit (events.js:182:7)
at emitOne (events.js:90:13)
at DestroyableTransform.emit (events.js:182:7)
at Glob.<anonymous> (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/index.js:38:16)
at Glob.g (events.js:273:16)
at emitOne (events.js:90:13)
at Glob.emit (events.js:182:7)
at Glob._finish (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:172:8)
at done (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:159:12)
at Glob._processSimple2 (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:652:12)
at /Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:640:10
at Glob._stat2 (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:736:12)
at lstatcb_ (/Users/macweb01/Sites/ccr/ras/node_modules/gulp-useref/node_modules/glob-stream/node_modules/glob/glob.js:728:12)
at RES (/Users/macweb01/Sites/ccr/ras/node_modules/inflight/inflight.js:23:14)
My html
task:
gulp.task('html', ['views', 'styles', 'scripts'], () => { return gulp.src([ 'app/**/*.html', '.tmp/**/*.html', '!.tmp/includes/**/*.html', '!.tmp/layouts/**/*.html', '!app/includes/**/*.html', '!app/layouts/**/*.html' ]) .pipe($.useref({searchPath: ['.tmp', 'app', '.']})) .pipe($.if('*.js', $.uglify())) .pipe($.if('*.css', $.cssnano())) .pipe($.if('*.js', $.rev())) .pipe($.if('*.css', $.rev())) .pipe($.revReplace()) .pipe($.if('*.html', $.htmlmin({collapseWhitespace: true}))) .pipe(gulp.dest('dist')); });
And my view
task:
gulp.task('views', () => { return gulp.src('app/**/*.html') .pipe($.nunjucksRender({ path: ['app/'] })) .pipe(gulp.dest('.tmp')) });
Can someone help me?
Thanks.
Add pretty option
Can you add pretty option to prettify html output? Or at least preserve indentation level in blocks and partials
Small Changes to Parent Template Not Detected
Sorry — re-opening this, as it’s not the IDE. I just tried editing and compiling the parent template in Vim and the same problem occurs.
Have a weird problem with nunjucks. When I make small changes to a comment section in a parent template, the ‘page’ template that extends the parent, does not get compiled (although the file to be compiled is being passed to nunjucks). If I type an extra word or two in the source parent template, all works as expected. I suspect this is a nunjucks problem, and not gulp-nunjucks-render — but thought I’d post here as well just in case I’m missing something obvious.
Here’s the issue I’ve posted with nunjucks… mozilla/nunjucks#811
Lodash issue
Please update lodash dependency to work around this issue:
lodash/[email protected]fe3d86b
else we get:
[00:16:43] 'compileTemplatesStatic' errored after 145 ms
[00:16:43] TypeError: _.defaultsDeep is not a function
at Object.module.exports (/Users/Zeno/Sites/Graffino/Projects/DotWhite/node_modules/gulp-nunjucks-render/index.js:18:15)
at compileTemplatesStatic (/Users/Zeno/Sites/Graffino/Projects/DotWhite/gulp/bundle.js:128:19)
at bound (domain.js:280:14)
at runBound (domain.js:293:12)
at asyncRunner (/Users/Zeno/Sites/Graffino/Projects/DotWhite/node_modules/async-done/index.js:36:18)
at _combinedTickCallback (internal/process/next_tick.js:67:7)
at process._tickDomainCallback (internal/process/next_tick.js:122:9)
How do I get an error when entering data incorrectly?
I have a config using plumber, but if I try to call data in my templates that does not exist in my data.json, then an empty string will just get into html, is it possible to catch an error when data is called incorrectly?
My config
function html() {
let data = {};
fs.readdirSync(paths.src.data).map((item) => {
if (path.extname(item).indexOf('.json') > -1) {
data = {...data, ...JSON.parse(fs.readFileSync(path.resolve(paths.src.data, item)))};
}
});
return src([
`${paths.src.html}/pages/**/*.*(njk|html|nunjucks)`,
`!${paths.src.html}/pages/**/_*.*(njk|html|nunjucks)`,
])
.pipe(plumber({errorHandler: notify.onError("Error: <%= error.message %>")}))
.pipe(nunjucksRender({
path: paths.src.html,
ext: config.html.extname,
data: validateJSON(data),
inheritExtension: false,
envOptions: {
watch: false,
},
manageEnv: (env) => {
// Filters
Object.keys(nunjucksFilters).forEach((name) => {
if (name.indexOf('esModule') > -1) {
return;
}
env.addFilter(name, nunjucksFilters[name]);
});
// Global functions
Object.keys(nunjucksFunctions).forEach((name) => {
if (name.indexOf('esModule') > -1) {
return;
}
env.addGlobal(name, nunjucksFunctions[name]);
});
},
loaders: null
}))
.pipe(dest(paths.build.html))
.pipe(
gulpIf(config.html.inject.css,
inject(
src(`${paths.build.styles}/**/*.css`, {read: false}), {
relative: true,
addPrefix: config.html.inject.prefix,
})
)
)
.pipe(gulpIf(!isDev(), htmlmin({
collapseWhitespace: true, // удаляем все переносы
conservativeCollapse: true, // сворачиваем все в 1 строку
removeComments: true // удаляем все комментарии
})))
.pipe(dest(paths.build.html))
.pipe(reload({stream: true}))
}
Json
{
"data": {
"en": {
"title": "Hello, bro",
}
}
}
Code example
<h2>{{ data[lang].header.title }}</h2>
-> <h2>Hello, bro</h2>
but
<h2>{{ data[lang].header.tite }}</h2>
-> <h2></h2>
I would like to get an error if .tite
does not exist
variables bleed between templates…
I’m using a fairly straightforward gulp task to render all files in a folder.
nunjucksRender.nunjucks.configure(['src/tmpl/']); return gulp.src('src/tmpl/*.htm') .pipe( plumber() ) .pipe( nunjucksRender() ) .pipe( gulp.dest( 'site/' ) );
But what I’m seeing is that variables (and macros) defined/set in one template are accessible in another…
If my src/tmpl/
folder contains two files:
src/tmpl/
page1.htm
page2.htm
and src/tmpl/page1.htm
contains:
{% set customAttr = "class='foobar'" %} <p {{customAttr}}>Hello World</p>
and src/tmpl/page2.htm
contains:
<p {{customAttr}}>Bonjour!</p>
then the rendered output for site/page2.html
becomes this:
<p class='foobar'>Bonjour!</p>
which makes life very difficult when one has lots of templates.
How to include php syntax in nunjucks?
In my project, I am trying to compile nunjucks file which is as follows:
stages.php
<?php
require_once 'index.php';
?>
{% extends "sections/_skeleton-content.html" %}
{% block content %}
<h1 class="stages-title">Stages</h1>
<div class="tests-list-container"> </div>
{% endblock %}
stages.php (compiled)
<!DOCTYPE html>
<head></head>
<body>
<h1 class="stages-title">Stages</h1>
<div class="tests-list-container"> </div>
</body>
As you can see, the php syntax is disappearing in compiled file. How to solve this?
Can path have multiple sources?
I want to keep page specific partial in page directory
Instead
path: 'src/templates'
this
path: 'src/templates', 'src/pages/**/partials'
is it possible? I tried that way but it’s not working.
[Question]How to give data on templates you only include?
Currently I’m doing this:
const PATHS = { srcFilesGlob: path.resolve(__dirname, "src/**/*"), pagesGlob: path.resolve(__dirname, "src/pages/**/*.njk"), partialsGlob: path.resolve(__dirname, "src/pages/**/**(.mjml).partial.njk"), rootDir: path.resolve(__dirname, "src"), componentsDir: path.resolve(__dirname, "src/components"), fontsDir: path.resolve(__dirname, "src/fonts"), layoutsDir: path.resolve(__dirname, "src/layouts"), pagesDir: path.resolve(__dirname, "src/pages"), stylesDir: path.resolve(__dirname, "src/styles"), buildDir: path.resolve(__dirname, "__build__"), outputDir: path.resolve(__dirname, "dist"), } return gulp .src([`${PATHS.pagesGlob}`, `!${PATHS.partialsGlob}`]) .pipe( nunjucks({ data: PATHS, path: [ PATHS.componentsDir, PATHS.fontsDir, PATHS.layoutsDir, PATHS.pagesDir, PATHS.stylesDir, ], envOptions: { noCache: true, tags: { blockStart: "<%", blockEnd: "%>", variableStart: "<$", variableEnd: "$>", commentStart: "<#", commentEnd: "#>", }, }, }), ) .pipe(gulp.dest(PATHS.buildDir))
It compiles well the files in pagesGlob
but also excludes partialsGlob
in order to have only pages as final files, not partials, in buildDir
.
In pages, I can do import
or include
of partials in nunjucks, it works well.
However, as partialsGlob
is exclude, data: PATHS,
isn’t given to those files, which means I can’t use variables like componentsDir
.
Do you have any idea to make it work?
Thank you.
Add Custom Filters
Hi @carlosl,
Do you have any examples of a custom filters working with your module? I have been trying without much luck. It seems to be something around the nunjucks environment and getting it setup properly with your module. Love some help with the below.
var render = require('gulp-nunjucks-render') var env = new render.nunjucks.Environment() env.addFilter('log', function(str){ console.log(str); return str; }); var htmlTask = function() { render.nunjucks.configure([path.join(config.root.src, config.tasks.html.src)], { watch: false }) return gulp.src(paths.src) .pipe(data(getData)) .on('error', handleErrors) .pipe(render(null, null, env)) .on('error', handleErrors) .pipe(gulpif(process.env.NODE_ENV == 'production', htmlmin(config.tasks.html.htmlmin))) .pipe(gulp.dest(paths.dest)) .pipe(browserSync.stream()) } gulp.task('html', htmlTask)
Thanks!
Missing the nl2br filter
I’m getting this error when trying to use the nl2br filter:
Error: filter not found: nl2br