Search code examples
expressview-helpersnunjucks

How to create view helpers in express with nunjucks?


I have an express project with nunjucks as my template engine. I have an inheritance permission system and on my User model there are methods to help me see the current user's permission level. Those methods currently are:

  • User.isAdmin() if User.permissionLevel == 0
  • User.isExpert() if User.permissionLevel <= 1

Problem is that with this current setup I'm not able to call those methods on my views. I wan't to have something similar to Rails Helpers, which are public methods that I can access anywhere on my project. How can I have a similar behaviour on express with nunjucks?


Solution

  • You can define res.locals.isAdmin before call res.render (e.g. inside a some middleware) and isAdmin will be accessable as global var.

    Another way is add a custom filter or function to return the user role.