Working with Jade & Express here.
'#{value.users}'
is an array.
'#{user.username}'
is a string.
Trying to do if '#{value.users}'.indexOf('#{user.username}')
If true, then I display a bunch of stuff, otherwise, shouldn't be rendered.
Jade is ok with the syntax, but even when #{value.users}'.indexOf('#{user.username}')
is falsy, the content within the if statement is being rendered.
For instance, if user.username = bob
, and value.users = ['tim', 'billy']
, the if
statement is passing, when it clearly shouldn't be.
What am I doing wrong?
Shouldn't it be #{value.users.indexOf(user.username)}
?
Any js commands inside #{}
is executed. You should be able to fit your entire expression inside a single '#{}'
By saying if '#{value.users}'.indexOf('#{user.username}')
the '#{value.users}'
is being serialised into a string and when using .indexOf()
it's searching within the string, rather than original array.
If you are using it in an if statement, why not just execute the js directly? eg.
- if ( value.users.indexOf(user.username) )
p some jade
- else
p alternate jade
https://github.com/visionmedia/jade#a8
Alternatively, you could use the underscore library.
http://underscorejs.org/#indexOf
If you want to use it inside Jade templates, be sure to require() it in your app or request locals.
I am not familiar with Jade, but wouldn't you need to test against != -1 or == 1?
str.indexOf('#{user.username}') ! = -1
or since you are testing against an array, something along the lines of.
array.toString().indexOf('#{user.username}') != -1
UPDATE: With the advent of ES6, I updated a little below
array.includes('#{user.username}') // returns true or false
str.includes('#{user.username}') // returns true or false
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With