How to check if array includes string in PUG template
Asked Answered
P

2

6

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
Palmary answered 22/3, 2018 at 15:46 Comment(1)
Can you post the content of example_array?Palmette
T
13

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

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

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

Terrilyn answered 22/3, 2018 at 16:13 Comment(1)
Do you mean parentheses instead of braces?Ripon
C
2

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!

Ceceliacecil answered 21/7, 2020 at 8:11 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.