Nunjucks - Add Custom Function
- Estimated read time: 3 min read
- Written by Chad Campbell on Oct 23rd 2016
As of the time of writing, this site used Nunjucks in the views. While creating one of my utility apps, specifically Delimiter, I needed a custom function. If you look at Delimiter, you'll notice that it takes up the entire width of the page. However, this post that you're currently reading uses a fixed width. I wanted to control the layout on the server-side, at design-time. For that reason, I wanted a custom function that looked like this:
This function is pretty straightforward.
container-fluid are class names in Bootstrap. I wanted to choose one of them based on the value of layout. But the real question was, how do I use this function within my views, which are rendered by Nunjucks? To do this, I knew I had to break down the problem into two steps.
The first step was to make the function available to the templates. That means, I had to figure out where in my Node app to place the
getLayoutClass that would make it accessible in my Nunjucks template (i.e. .html file).
In my pursuit of trying to figure that out, I discovered the
addGlobal function. This function let's you add a globally scoped value across all of your Nunjucks views. To actually add it, I chained a call to
addGlobal onto my
configure call. That means when I wired up Nunjucks in my app, it ended up looking like this:
Same function as defined before. Just written slightly differently. My next step was to actually call this function from my template.
I knew I would need the value in a couple of spots in my template. For that reason, I created a variable in my template using the set tag. I used the
set tag in my template like this:
layoutClass variable was created and set, I could use it in the template. I ended up using this variable like this:
With these two steps, I was able to create and use a reusable custom function in Nunjucks. The trickier part was probably step 1. Still, I hope you found this post helpful. If you did, I hope you'll check out some of the training courses I've created. If there are topics you're curious about, please feel free to mention them in the comments below. Thanks for reading.