Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if key exists in array in nunjucks template (Node JS)

I am creating an application in Node Js using Nunjucks template engine and I have to apply permissions on pages to show add, edit and delete links.

For this I have implemented an array of permissions like below :

var user_params = ['add_user', 'edit_user', 'delete_user'];

Now I want to check on pages that add_user exists in user_params array or not just like we do in php

in_array('add_user', user_params)

But I am being able to perform this task in nunjucks. So can anyone help me out ?

Thanks in advance

like image 245
Ankit Avatar asked Apr 11 '17 07:04

Ankit


2 Answers

You should be able to do this:

{% if 'add_user' in user_params %}
   do stuff in html
{% endif %}

For indexOf, I'm not sure that works but even if it did, if zero evaluates to false that's not good either if you're testing the first row. would also need to check > -1

like image 95
WakeskaterX Avatar answered Nov 09 '22 23:11

WakeskaterX


The only way I found is looping through the array like so:

{% for param in user_params %}
    {% if param==='add_user' %}
        do stuff in html
    {% endif %}
{% endfor %}

Ugly and full of holes, but will fit most use cases.

You're probably better off making a custom filter

like image 42
Sjeiti Avatar answered Nov 10 '22 01:11

Sjeiti