如何在PUG模板中检查数组是否包含字符串

6

我正在使用NodeJS和Express以及PUG视图引擎。

我试图检查一个数组是否包含某个字符串。我已经尝试过内置的JavaScript方法,例如:

array.includes(str)
array.indexOf(str) > -1.

然而,这两个选项似乎都不起作用。如何在PUG中检查数组是否包含特定字符串?

if example_array.length > 0
  span() Array contains elements! // This works and appears on page
  if example_array.includes('example string') // This does not work
    span() Array includes example string! // This does not appear on page

1
你能发布example_array的内容吗? - Ele
2个回答

12

如果您想在模板中运行内联JS,则必须将代码标记为未缓冲。

https://pugjs.org/language/code.html#unbuffered-code
  if example_array.length > 0
     span() Array contains elements! 
     - if (example_array.includes('example string'))
       span() Array includes example string! 

请注意第三行的 "if" 前面的 "-" 符号。

由于这是一个文字 js 表达式,因此现在需要使用括号。


你是不是指的是圆括号而不是花括号? - Sean

1
这个问题让我忙了几个小时,所以我想分享一下我的解决方案。虽然直接检查字符串的答案是正确的,但请记住,如果您从变量中进行检查,则可能需要添加.toString()
- if (example_array.includes(myVariable.toString()))

希望这能为某人节省一些时间!

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接