Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using indexOf in Jade

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?

like image 635
Jacques Tardie Avatar asked Feb 26 '13 19:02

Jacques Tardie


2 Answers

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.

like image 81
Mike Causer Avatar answered Oct 23 '22 04:10

Mike Causer


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
like image 36
james emanon Avatar answered Oct 23 '22 03:10

james emanon