Search code examples
javascriptnode.jsnunjucks

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.


Solution

  • 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)