简体   繁体   中英

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

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM