Search code examples
javascriptconditional-statementshandlebars.jshandlebarshelper

Need Handlebars helper to check if value is > 1 or < 2 then render code depending upon which condition is met


I have setup a login route which saves user data that includes a value under the key permission_id. This permission_id must be checked to see if it is > 1 or < 2. If it is < 2, I want to render the first piece of HTML, else, render the second. This permission value is being used to determine if the user can see certain content or not.

I currently have a helper written as follows in my server file:

const hbs = exphbs.create({
    // create custom helper 
    helpers: {
      permissionCheck: function(value){
        if (value < 2) {
          value = true;
        } else {
          value = false;
        }
      }
    }
});

In my handlebars file, i am attempting to write the following:

{#permissionCheck req.session.permission_id }}
{{else}}
{{/permissionCheck}}

Any suggestions?

I have tried to change the syntax to include my helper inside of () as {{#if (permissionCheck req.session.permission_id)}} but to no avail.

I am not sure how to write a helper to behave as a conditional statement in this manner but I need to be able to check this variable to render content appropriately.


Solution

  • First, as @Matthias stated in the comments, you must return a value from your helper. For example:

    function (value) {
      return value < 2;
    }
    

    Second, your helper is not checking that value is greater than one, even though you said in your post that this is a requirement. Therefore, the helper should become:

    function (value) {
      return 1 < value && value < 2;
    }
    

    Third, you are not understanding the difference between Handlebars' Block and Inline helpers. When you invoke your helper with {{#permissionCheck req.session.permission_id }}, you are invoking it as a Block helper. However, since your helper returns a simple Boolean value, it is an Inline helper.

    Therefore, we need to invoke it as an Inline helper from our template and we can use its returned value as the argument to an if (Block) helper which will determine what gets rendered. Example:

    {{#if (permissionCheck req.session.permission_id)}}
      <p>Secret stuff!</p>
    {{else}}
      <p>Permission is required</p>
    {{/if}}
    

    I have created a fiddle for reference.