Looking for a Handlebars helper that can determine if a value is greater than 1 or less than 2, and then render specific code based on which condition is satisfied

My login route is saving user data with a permission_id key that needs to be checked to determine whether it is greater than 1 or less than 2. Depending on the value of permission_id, I need to render different HTML content to allow or restrict access to certain content for users.

To achieve this, I have created a helper in my server file:

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

Now, in my handlebars file, I am trying to implement the helper like this:

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

However, I have been facing some challenges in getting the syntax right, as I have attempted {{#if (permissionCheck req.session.permission_id)}} without success.

I am struggling to create a helper that behaves like a conditional statement to properly check the permission_id variable and display the relevant content accordingly.

Answer №1

To start, as mentioned by @Matthias in the comments, it is crucial to ensure that your helper function returns a value. Take this example:

function (value) {
  return value < 2;
}

Furthermore, your helper must explicitly check if the value is greater than one, despite your initial statement indicating so. Therefore, modify your helper function to:

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

Additionally, it appears there might be some confusion regarding Handlebars' Block and Inline helpers. When calling your helper with

{{#permissionCheck req.session.permission_id }}
, it is treated as a Block helper. However, since your helper returns a basic Boolean value, it should be considered an Inline helper.

To utilize it correctly, invoke the helper as an Inline helper within the template. Use the returned value as an argument for an if (Block) helper to determine the rendering outcome. See the example below:

{{#if (permissionCheck req.session.permission_id)}}
  <p>Confidential content!</p>
{{else}}
  <p>Permission required</p>
{{/if}}

I have included a fiddle for your reference.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Contrast in functionality between a pair of variables within a controller

Could you please clarify the distinction between two variables a1 and a2: app.controller("someCtrl",function(){ this.a1=somevalue; var a2=somevalue; }); Also, can you explain the lifespan of variable a2? ...

Reorganizing array of objects in JavaScript

Currently, I am tackling a challenge within a ReactJS application. My task involves extracting JSON data related to various products and restructuring this information for the purpose of categorization and displaying it accordingly. Despite my attempts wi ...

"Combining background images with javascript can result in displaying visual elements

Hello! I am in need of assistance with a CSS + Javascript fog effect that I have developed. It is functioning properly on Firefox, Opera, and Chrome but encountering issues on IE and Edge browsers. The effect involves moving two background images within a ...

Angular 2 module transpilation services

In my angular 2 application, there is a module called common. Here is how the project structure looks like: main --app /common --config //.ts configs for modules --services //angular services --models --store //ngrx store /co ...

Error alert: Index not defined!

I have a dropdown select that needs to be populated with values from a database. I then need to validate the selected value using a JavaScript function, which is already implemented. The dropdown list has two columns: one for ID identifiers and another fo ...

What is the best way to alternate between displaying HTML content with v-html and plain text in Vue.js?

I need a way to switch between v-html and plain text in Vue.js v2. Here's what I have so far: HTML <div id="app"> <h2 v-html="html ? text : undefined">{{html ? '' : text}}</h2> <button @click=&qu ...

Utilizing nested array object values in ReactJS mappings

My JSON API is set up to provide a data structure for a single record, with an array of associations nested within the record. An example of the response from the api looks like this: { "name":"foo", "bars":[ { "name":"bar1" ...

Unable to transmit information using Postman for registration API

I have been struggling to send data via a POST request to the register API, but for some reason, the data is not being transmitted. I have tried adjusting the settings on Postman, tinkering with validation rules, and various other troubleshooting steps, ye ...

Enabling the submit button only when text is entered in the text fields using jQuery

I have a script that automatically submits a form when two textfields are filled using variables from local storage. The script checks if the variables for email and password are not null before submitting. if (localEmail != null && localPwd != null) { ...

Swap out a paragraph with a city name fetched from a JSON file

While working on a weather app, I encountered an issue. The app needs to automatically detect the user's location and display the appropriate temperature along with the city name. I have been trying to fetch data from JSON to replace the placeholder t ...

The React.js project I created is showcased on GitHub pages and has a sleek black design

After developing a project using React.js and deploying it on github pages, everything was functioning smoothly. However, I encountered an issue where the screen turned black after logging in and out multiple times. Are there any suggestions on how to reso ...

Utilizing Selenium and Python to extract data from JavaScript tables via web scraping

I've come across numerous articles about Web Scraping, but I'm still struggling to figure out how to locate specific elements on a website. The site where I want to scrape the tables can be found here: My target tables are: "TB01," "TB02," "TB0 ...

Jquery Droppable issue arising with dynamically added DIVs

I am facing a similar issue as described in this question and this one I am trying to implement drag-and-drop and resize functionality. It is working fine for static elements, but I encounter issues when adding dynamic divs. The resize property works prop ...

Bring in styles from the API within Angular

My goal is to retrieve styles from an API and dynamically render components based on those styles. import { Component } from '@angular/core'; import { StyleService } from "./style.service"; import { Style } from "./models/style"; @Component({ ...

Dealing with Large JSON Strings in ASP.NET MVC Views

Large JSON Objects (approximately 1.5 MB) are received in Controller C1. They are then converted to strings and stored in a hidden label in View V1. The JSON data in V1 is utilized by parsing it in JavaScript J1. An occurrence of Out of Memory Excepti ...

Tips for effectively using $interval for ongoing polling in AngularJS?

Within my Angular codebase, I have implemented long polling functionality using the following code snippet: var request = function() { $http.post(url).then(function(res) { var shouldStop = handleData(res); if (!shouldStop()) { ...

Traversing a hierarchical structure and building a REACT user interface based on it

Currently, I am tasked with a project that involves working with a hierarchy tree. The goal is to loop through the data provided by the tree and create a user-friendly UI representation of the hierarchy for seamless navigation. Here's an illustration ...

Routing with nested modules in Angular 2 can be achieved by using the same

Encountering a common issue within a backend application. Various resources can be accessed through the following routes: reports/view/:id campains/view/:id suts/view/:id certifications/view/:id Note that all routes end with the same part: /view/:id. ...

Retrieving a local variable within an AngularJS controller

Examining the code provided below: app.controller('Controller', function($scope, $http){ $scope.rep = []; $scope.tot = { name: '', marketValue: 0, cash: 0, legend: 'none' }; ...

Export a function within a function to be used in another file in Javascript

I'm encountering an issue regarding exporting a function within a function to another function in a separate file, while working with the React framework. The code snippet provided below is not functioning as expected, despite my attempts to troubles ...