mozilla / nunjucks

A powerful templating engine with inheritance, asynchronous control, and more (jinja2 inspired)
https://mozilla.github.io/nunjucks/
BSD 2-Clause "Simplified" License
8.58k stars 640 forks source link

Improve docs for programmatic templates precompiling #777

Open kolesnikova-tavi opened 8 years ago

kolesnikova-tavi commented 8 years ago

I'm trying to use gulp to precompile templates. My plan is: 1) Precompile templates to some files; 2) Require; 3) Use render.

I'm doing something like this (gulpfile.js):

    return merge(dirs.map(function(dir) {
        return gulp.src(path.join(dir, '/*.html'))
            .pipe(pipeError('Precompile Folder Templates'))
            .pipe(gulpNunjucks.precompile({
                path: 'src/templates/modules',
                options: {
                    noCache: true
                }
                context: {
                    SOME_VARS: '',
                    SOME_FUNCTIONS: function() {
                    }
                },
                extendEnv: function(env) {
                    // ...
                }
            }))
            .pipe(concat('templates.js'))
            .pipe(gulp.dest(path.dirname(dir)));
        }));

gulpNunjucks.precompile does this:

// ...
settings.loader = new nunjucks.FileSystemLoader(settings.path);
settings.env = new nunjucks.Environment(settings.loader, settings.options);
settings.extendEnv(settings.env);
// ...
let output = 'exports["<%= file.stem %>"]=<%= template %>;';
// ...
// TODO: almost what I need (*)
let result = nunjucks.precompileString(file.contents.toString(), {
    env: settings.env,
    name: file.stem,
    context: settings.context  // TODO: need pass context (**)
});
file.contents = new Buffer(result);
file.path = gutil.replaceExtension(file.path, '.js');

Then in my node project js-file: let templates = require('./moduleName/templates');

And I need something like this:

// TODO: need a way to render (***)
templates.loginForm.render(context);
templates.regForm.render(context);

() This way to use precompiled files with tag script. How can I get function without using window object? () How can I pass context? () I can't see how use precompiled templates.

Is any way? Thanks!

rhengles commented 8 years ago

Please take a look at this gist I created:

https://gist.github.com/rhengles/2a4b4df5aedb063f6a8d79029f66f47b

Maybe we could use this issue to improve the documentation in this regard.

carljm commented 8 years ago

PR for improved documentation would be most welcome!

kolesnikova-tavi commented 8 years ago

It works! Thanks a lot! Can I pass variables to precompile method?

rhengles commented 8 years ago

@kolesnikova-tavi No. You can add filters and extensions [1], but the context variables are only used on the render method.

[1] http://mozilla.github.io/nunjucks/api.html#precompile

kolesnikova-tavi commented 8 years ago

it's a pity. OK, thank you!