如何在Nunjucks模板中调用JavaScript函数更新过滤器?以及能否在Nunjucks模板中调用JS函数并传递变量?
1. How to Call a JavaScript Function to Update a Filter in Nunjucks
Absolutely! You can call JavaScript functions directly within Nunjucks templates to generate dynamic values that feed into filters. Here's a step-by-step breakdown:
First, Expose Your JavaScript Function to Nunjucks
You need to make your function available to the template either as a global or via the render context. For Node.js environments:
const nunjucks = require('nunjucks'); const env = nunjucks.configure('views'); // Option 1: Add as a global function env.addGlobal('orderBy', () => { // Replace with your logic to determine the filter parameter return 'lastUpdated'; // Example: sort by last updated date }); // Option 2: Pass via render context res.render('your-template', { orderBy: () => 'lastUpdated' });
Then Call the Function in the Template
Once the function is accessible, you can invoke it to set a variable, which you then use with your filter—just like your example demonstrates:
{% set filterParam = orderBy() %} {% for item in items | sort(true, true, filterParam) %} <!-- Render your sorted items here --> {% endfor %}
This dynamically sets the sorting parameter for the sort filter using the return value of your JavaScript function.
2. Can You Call a JavaScript Function in Nunjucks and Pass Variables?
Yes, definitely! Nunjucks supports passing template variables, context data, or literal values to JavaScript functions. Here's how:
Example: Pass Variables to a Function
First, update your JavaScript function to accept parameters:
env.addGlobal('getSortKey', (contentType) => { // Logic based on the passed variable switch(contentType) { case 'articles': return 'publishDate'; case 'comments': return 'createdAt'; default: return 'id'; } });
Then call the function in your template with variables:
{# Pass a template variable #} {% set currentContentType = 'articles' %} {% set sortKey = getSortKey(currentContentType) %} {# Or pass a context variable directly #} {% set sortKey = getSortKey(page.contentType) %} {# Use the result in your filter #} {% for item in items | sort(true, true, sortKey) %} <!-- Render items sorted by the dynamic key --> {% endfor %}
You can also pass multiple parameters just like regular JavaScript calls: getSortKey(param1, param2, param3).
内容的提问来源于stack exchange,提问作者DMS

