D
D
Dima Polos2018-12-20 13:12:09
HTML
Dima Polos, 2018-12-20 13:12:09

How to include a file inside a document in nunjucks?

In my project, nunjucks is connected like this

let gulp           = require('gulp');
let nunjucksRender = require('gulp-nunjucks-render');
let plumber        = require('gulp-plumber');
let gulpif         = require('gulp-if');
let changed        = require('gulp-changed');
let prettify       = require('gulp-prettify');
let frontMatter    = require('gulp-front-matter');
let config         = require('../config');

function renderHtml(onlyChanged) {
    nunjucksRender.nunjucks.configure(config.src.templates, {
        watch: false,
        trimBlocks: true,
        lstripBlocks: false
    });

    return gulp
        .src([config.src.templates + '/**/[^_]*.html'])
        .pipe(plumber({
            errorHandler: config.errorHandler
        }))
        .pipe(gulpif(onlyChanged, changed(config.dest.html)))
        .pipe(frontMatter({ property: 'data' }))
        .pipe(nunjucksRender({
            PRODUCTION: config.production,
            path: [config.src.templates]
        }))
        .pipe(prettify({
            indent_size: 4,
            wrap_attributes: 'auto', // 'force'
            preserve_newlines: false,
            // unformatted: [],
            end_with_newline: true
        }))
        .pipe(gulp.dest(config.dest.html));
}

gulp.task('nunjucks', function() {
    return renderHtml();
});

gulp.task('nunjucks:changed', function() {
    return renderHtml(true);
});

gulp.task('nunjucks:watch', function() {
    gulp.watch([
        config.src.templates + '/**/[^_]*.html'
    ], ['nunjucks:changed']);

    gulp.watch([
        config.src.templates + '/**/_*.html'
    ], ['nunjucks']);
});

In the template, I call include like this:
{% include "../img/svg/ico.svg" %}
Error: gulp-notify: [Compile Error] (unknown path)
Error: template not found: ../img/svg/ico.svg
The path is correct, the names are too. If you throw the icon into the templates folder, where nunjucksRender is aimed, then everything is OK, he doesn’t want to look further than the templates folder, how can he show the world outside the templates folder?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
D
Demian Smith, 2018-12-20
@dimovich85

You will have to be upset. Nunjucks does not look "outside of the box". This is reported by one of the authors of the library. Discussed here:
https://github.com/mozilla/nunjucks/issues/326#iss...
Relative paths can be used, but only if they are within paths: []. So either move the file to templates or add '...img/svg' to the paths array. My condolences.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question