Setting up nunjucks for using custom filters with express

My attempt to implement a custom filter with nunjucks, as per the documentation, resulted in an error message:

Error: filter not found: my_filter_here

Here are the configurations I have:

index.js

const express = require('express');
const nunjucks = require('nunjucks');

const port = 3000;
const app = express();

nunjucks.configure('views', {
  autoescape: true,
  express: app
})

app.set('view engine', 'html');

const env = new nunjucks.Environment();

env.addFilter('is_undefined', function(obj) {
  return typeof obj === 'undefined';
});

For template rendering, I am using

res.render('register.html', {errors: errors});

In my template, I have set it up like this:

{% if errors|is_undefined %}
  // do something
{% endif %}

The error I am facing is: Error: filter not found: is_undefined

Some suggestions on Stack Overflow mentioned using env.render() instead of res.render, but changing it caused my HTML page not to render. Any solutions to correct this issue?

Thank you in advance. :)

Answer №1

As per the documentation: configure function will provide an instance of Environment. This means

const env = nunjucks.configure('views', {
  autoescape: true,
  express: app
})

env.addFilter('is_undefined', function(obj) {
  return typeof obj === 'undefined';
});

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Modifying the array structure will deselect all individual <Input> elements that have been iterated

Hoping to create a system for adding/removing sub-items with buttons that increment/decrement slots in an array, where input fields are automatically added and removed: <div *ngFor="let item of itemsInNewOrder; let i = index"> <input [(ngModel) ...

Achieving the validation with a bold red border

Hi, I'm currently learning React and I've been using regular JavaScript to validate my form. Here's a snippet of how I'm doing it: <TextField label="Title" variant="outlined" si ...

What is the best way to reposition the caret within an <input type="number"> element?

How can I make the caret move when an input is clicked? The code I found works with text, but not with number. Also, is there a way to pass the length without specifying a value (e.g. 55) in the parameters? HTML <input type="number" name="cost" value= ...

Error encountered while using XLSX.write in angular.js: n.t.match function is not recognized

I've encountered an issue while trying to generate an .xlsx file using the XLSX library. The error message I received is as follows: TypeError: n.t.match is not a function at Ps (xlsx.full.min.js:14) at Jd (xlsx.full.min.js:18) at Sv (xlsx.full.min ...

Vue: Customize data based on userAgent

As a newcomer to VUE, I am attempting to dynamically modify the disabled value based on the userAgent in order to display or hide the paymentMethod: data() { return { paymentMothods: [ { name: 'Visa che ...

Exploring and accessing the properties of objects in JavaScript

While attempting to access the email and password fields, an unexpected '0' seems to have appeared. The object retrieved from RethinkDB appears fine without this '0'. However, when using Lodash's _.assign() method like so: var use ...

express-session creates a fresh session each time it is initiated, but the session is not saved permanently

In my setup, I am using express for the backend running on localhost:8080 For the frontend, I have employed react on localhost:3000 There is no proxy in use; just a simple http://localhost:3000/roster request to http://localhost:8080/ Cross-origin and head ...

Updating with Setstate

Refreshing the page with Setstate, registering twice and doubling the count of both heads and tails counter every time on click instead of adding just +1 class CoinFlip extends Component { constructor(props) { super(props); ...

What are the steps for testing React components when they are wrapped by ThemeProvider/withStyle?

Is there a way to properly test a component that is wrapped with withStyle, as it seems the theme object does not pass through the component. Any suggestions on best practices for achieving this? I am considering using createShallow() and dive() methods t ...

Having difficulty rendering JSON data on an HTML webpage

Currently, I am working on an API App that utilizes the Foursquare API. With the help of my getRequest function, I am able to obtain results in JSON format, which are then displayed in my console.log. However, the challenge lies in parsing the data from J ...

Accessing JSON files locally using JavaScript in IE and Firefox

I am a beginner in JavaScript and currently working on a small HTML page that will be run locally. I have a string in JSON format that I need to store and load as a file on the hard drive. I have managed to store the string using the following code snippe ...

Simple way to automatically reload your script using an npm server

Testing out a sample javascript code snippet. Locating a script named simple.js in the demos directory. Executing the demo using the command yarn build-demos && http-server demos/ The script simple.js is compiled to simple_bundle.js and the serv ...

Utilize AJAX to dynamically insert data into the database

I have created a JSP page that displays records, and now I am looking to include a dynamic link or button in the JSP that allows inserting data into the database without needing to refresh the page. This link should open a pop-up window with input fields ...

The Vue.js scripts and styles declared in the index.html file seem to be malfunctioning

I acquired a theme that includes html, css3, and js files, and I included the file path as shown below: <!-- Basic --> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <title>Porto - Responsive HTML5 Te ...

HTML Tutorial: A Beginner's Guide to Invoking REST API

Hi there! I'm new to APIs and struggling to grasp the concept. The tutorials online seem more complex than necessary. Here's what I need help with: I want to create a basic webpage that allows me to search for information using the Pokemon API a ...

What is the best way to organize large amounts of data into an array?

I am currently working on developing a unique version of wordle using javascript and html. In order to do this, I require a comprehensive list of all possible wordle words stored in an array format. Although I have the words listed within a document contai ...

transferring data from JavaScript to PHP variables

Currently, I am working on a project that involves using ajax to access the database asynchronously. The value retrieved is stored in a JavaScript variable like this: var content=xmlhttp.responseText; My next step is to pass this value to the PHP module ...

Using PHP to send variables to an AJAX function via parameters

I've encountered an issue while attempting to pass 4 variables through the parameters of the ajax function. The variables I'm trying to pass include the URL, action, ID, and timeout in milliseconds. Unfortunately, the function is not accepting th ...

Processing of hierarchical JSON structure

I have a JSON array that I am trying to duplicate only once while keeping it unique. Here is the code I have attempted: return_data = {}; return_data.planner = [{ "date": "2019-08-30T12:10:08.000Z", "event": [{ "name": "Event 1", "col ...

differences between using form's get method and sending an angular $http.get request

When trying to make a GET request to a specific URL from my Angular frontend to an ExpressJS backend, I encountered some interesting behavior. In the frontend code snippet below: <li> <a ng-click="givequiz()">GiveQuiz</a> </l ...