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

喜欢而已 提交于 2019-12-21 04:54:12

问题


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.


回答1:


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)


来源:https://stackoverflow.com/questions/26443028/how-to-use-nunjucks-macros-in-the-browser-client-side

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!