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
2 Answers
Reset to default 13If 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!