最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - How to check if array includes string in PUG template - Stack Overflow

programmeradmin4浏览0评论

I am using NodeJS with Express and the PUG view engine.

I am attempting to check if an array contains a certain string. I have tried the builtin javascript methods such as:

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

However neither of these options seem to work. How can I check if an array contains a certain string in 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

I am using NodeJS with Express and the PUG view engine.

I am attempting to check if an array contains a certain string. I have tried the builtin javascript methods such as:

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

However neither of these options seem to work. How can I check if an array contains a certain string in 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
Share Improve this question asked Mar 22, 2018 at 15:46 pengzpengz 2,4716 gold badges54 silver badges95 bronze badges 1
  • 1 Can you post the content of example_array? – Ele Commented Mar 22, 2018 at 15:47
Add a ment  | 

2 Answers 2

Reset to default 13

If you want to run inline JS in your template you have to mark your code as unbuffered. https://pugjs/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! 

Note the "-" in front of the "if" on line 3.

Since this is a literal js expression now the parantheses are required aswell.

This kept me busy for hours so I wanted to share my own solution. While the answer is correct when checking for a string directly, remember you may need to add .toString() if you're checking from a variable:

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

Hopefully this saves someone some time!

发布评论

评论列表(0)

  1. 暂无评论