Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to check if array includes string in PUG template

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
like image 710
pengz Avatar asked Jan 02 '23 15:01

pengz


1 Answers

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.

like image 92
alexloehr Avatar answered Jan 05 '23 14:01

alexloehr