Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use nunjucks macros in the browser client-side?

I'm able to use client-side templating for nunjucks as I precompile from node.js and expose JS template files. I call the client-side templates like so:

nunjucks.render('partials/some-template.html', { abc: 123 })

and get a string back.

How can I call macros as I've tried but am doing this wrong. Macros are first declared on the page in terms of node.js then called successive times for example in Node.js:

{% include 'macros/checkbox.html' %}
...
{{ checkbox('you cool?', 'cool', false) }}
{{ checkbox('you collected?', 'collected', false) }}

But not sure how to get the macro then call it again and again in client-side. I did make an effort to go through the inspection in the console so far but no luck.

like image 347
King Friday Avatar asked Oct 18 '14 18:10

King Friday


People also ask

Why use Nunjucks?

Nunjucks calls itself “A rich and powerful templating language for JavaScript”, which sounds about right. It's not intentionally super lightweight like Mustache or the slightly more robust (but still pretty light) Handlebars. It's a full-on language, packed with all kinds of stuff you might want when writing templates.

How does Nunjucks pass data?

You can use gulp-data which allows you to pass json files to the task runner you're using to render Nunjucks.

What is Nunjucks template?

Nunjucks is rich and powerful template engine for JavaScript. Nunjucks is developed by Mozilla and is maintained by Node JS Foundation. Nunjucks can be used in Node and browser. Its is inspired by Jinja2 ( a web template engine for python ).


1 Answers

When I wanted to render a macro on the client side, I used the nunjucks.renderString method to import the file containing the macros and then call it -- all in one go. My usecase is rendering a macro into HTML, then adding it onto the page using Javascript. A sample use case would be:

var renderString = "{% import 'packageForms.html' as forms %} \n";
renderString = renderString + '{{ form.packageForm("task") }}';
var renderedHTML = nunjucks.renderString(renderString);
$('#page').append(renderedHTML)
like image 169
John O'Sullivan Avatar answered Oct 10 '22 15:10

John O'Sullivan