简体   繁体   English

检查nunjucks模板中的数组是否存在键(Node JS)

[英]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. 我正在使用Nunjucks模板引擎在Node Js中创建一个应用程序,我必须在页面上应用权限来显示添加,编辑和删除链接。

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 现在我想查看add_user存在于user_params数组中的页面,或者不像我们在php中那样

in_array('add_user', user_params)

But I am being able to perform this task in nunjucks. 但我能够在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. 对于indexOf,我不确定是否有效,但即使它确实有效,如果零评估为false,那么如果你正在测试第一行也不好。 would also need to check > -1 还需要检查> -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 你最好自己制作一个自定义过滤器

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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