Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

#if Statements in Handlebars

Ok, I know this is super basic, but I've been staring at it for 2 days and can't see why it is not working. I am using Handlebars IF helpers to conditionally render a template.

Here is the HTML:

<head>
    <title>flash</title>
</head>

<body>
    {{#if isTrue}}
        {{> hello}}
    {{else}}
        {{> goodbye}} 
    {{/if}}
</body>

<template name="hello">
    <h1>Hello!</h1>
</template>

<template name="goodbye">
    <h1>Goodbye!</h1>
</template>

Here is the simple coffee file:

isTrue = true

I expect the {{> hello}} template to render, but no luck. I just get the {{> goodbye}} template. It's odd since I have other projects where I have done this successfully. I must be missing something obvious here.

like image 815
ppedrazzi Avatar asked Mar 06 '13 16:03

ppedrazzi


3 Answers

The isTrue variable needs to be in a template for it to work. So, put the body contents in a template:

<body>
    {{> body}}
</body>

<template name="body">
    {{#if isTrue}}
        {{> hello}}
    {{else}}
        {{> goodbye}} 
    {{/if}}
</template>

And then you can define isTrue like this:

Template.body.helpers
  isTrue: -> true
like image 124
Sjoerd Visscher Avatar answered Oct 12 '22 02:10

Sjoerd Visscher


Note:

Template.body.isTrue = -> true

is now deprecated.

The new syntax looks like this:

Template.test.helpers({
  'isTrue': function(){
    return true;
  }
});

It should still work but if you open your console it will give you a warning about the syntax.

like image 21
Jordan Schreuder Avatar answered Oct 12 '22 02:10

Jordan Schreuder


with Meteor 1.2.0.2 you can do it like this

Template.hello.helpers({
   isTrue() { return true }
});
like image 39
phtn458 Avatar answered Oct 12 '22 01:10

phtn458