【问题标题】:How to check if array includes string in PUG template如何检查数组是否在 PUG 模板中包含字符串
【发布时间】:2018-09-01 03:27:18
【问题描述】:

我正在使用带有 Express 和 PUG 视图引擎的 NodeJS。

我正在尝试检查一个数组是否包含某个字符串。我已经尝试过内置的 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

【问题讨论】:

  • 可以发example_array的内容吗?

标签: javascript node.js string express pug


【解决方案1】:

如果您想在模板中运行内联 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! 

注意第 3 行“if”前面的“-”。

由于这是一个文字 js 表达式,现在括号也是必需的。

【讨论】:

  • 你的意思是括号而不是大括号?
【解决方案2】:

这让我忙了好几个小时,所以我想分享我自己的解决方案。虽然直接检查字符串时答案是正确的,但请记住,如果您从变量中检查,您可能需要添加 .toString()

- if (example_array.includes(myVariable.toString()))

希望这可以节省一些时间!

【讨论】:

    猜你喜欢
    • 2023-02-18
    • 2013-08-16
    • 1970-01-01
    • 2018-05-04
    • 2012-08-11
    • 1970-01-01
    • 1970-01-01
    • 2021-12-03
    • 2022-06-30
    相关资源
    最近更新 更多