0

I have an app running on Node, Express and express-handlebars. The variable is a result of a query assigned to res.locals and condition helper "ifCond" like this one. The code that needs to be rendered is a in a partial. The problem is that helper is not working when using a variable with it:

//getting the variable works
{{groups}} // Group2 

//works with standart block helper
{{#if groups}}1{{else}}2{{/if}} //  1  

//helper is working
{{#ifCond 5 "==" 5}}equal{{else}}not equal{{/ifCond}} //equal

//not working when using variable with helper
{{#ifCond groups "==" Group2}}equal{{else}}not equal{{/ifCond}} //not equal

What can cause it not to work with a helper? Thank you.

ASem
  • 142
  • 3
  • 16
  • 1
    I think you need to put `Group2` in quotes: `{{#ifCond groups "==" "Group2"}}` since you're trying to pass a string to your helper. – jfriend00 Sep 02 '17 at 14:11
  • Also, is `groups` really a global variable? Or are you passing it into `res.render()` as a property of the options object? You shouldn't be using global variables in page rendering. – jfriend00 Sep 02 '17 at 14:18
  • Yes it worked, thank you, but it strange, since I'm not using "===" it has to be careless whether it is a string or not. I am not using directly in res.render(); a pass it to res.locals, so it can be available globally as a property of a user. to be more exact it is avilabe only inside (req, res) for a timelife of a function. I cant do that? – ASem Sep 02 '17 at 14:32
  • It's not the `==` that cares. It's the template parsing. If you don't put quotes around it, it tries to find a variable with that name and there isn't one. Without quotes around it, it is treated like `groups` right before it. – jfriend00 Sep 02 '17 at 14:42
  • Using `res.locals` is fine. Using an actual global variable would be wrong (since multiple requests in flight at the same time could conflict), but even though your question mentions `global variable`, it doesn't sound like you are actually using a global variable - that's what had me confused. – jfriend00 Sep 02 '17 at 14:47
  • Ok, thank you. What I ment is to use it globally in templates. May I ask one more question? According to how the template works, does it mean that using "===" in ifCond makes no sence since it defines everything as n object? – ASem Sep 02 '17 at 14:58
  • 1
    Looking at the code for your helper, `===` would still make a difference if you were comparing a string to a number. – jfriend00 Sep 02 '17 at 15:03

1 Answers1

1

You need to put Group2 in quotes so it is treated as a string by the template parser:

{{#ifCond groups "==" "Group2"}} 

since you're trying to pass a string to your helper. When you don't put quotes around it, the handlebars parser tries to resolve it as a variable name just like with groups right before it.

jfriend00
  • 683,504
  • 96
  • 985
  • 979