Search code examples
node.jshandlebars.jsexpress-handlebars

use helper of handlebars-express in view


I am using nodejs as a backend and the handlebars-express library

I have 3 files, my index.js, loginController.js and loginTemplate.handlebars

In my index.js I have declared handlebars like this

const handlebars = require('express-handlebars');
const server = express();

var hbs = handlebars.create({
  helpers: {
    getStringifiedJson: function (value) {
      return JSON.stringify(value);
    },
    ifCond: function (v1, operator, v2, options) {
      switch (operator) {
        case '==':
          return v1 == v2 ? true : false;
        case '===':
          return v1 === v2 ? true : false;
        case '!=':
          return v1 != v2 ? true : false;
        case '!==':
          return v1 !== v2 ? true : false;
        case '<':
          return v1 < v2 ? true : false;
        case '<=':
          return v1 <= v2 ? true : false;
        case '>':
          return v1 > v2 ? true : false;
        case '>=':
          return v1 >= v2 ? true : false;
        case '&&':
          return v1 && v2 ? true : false;
        case '||':
          return v1 || v2 ? true : false;
        default:
          return false;
      }
    },
  },
  layoutsDir: __dirname + '/src/views',
});

server.set('view engine', hbs);

In my loginController I have this

const { getTemplate } = require('../services/handlebarsService');

    getTemplate('loginController/loginTemplate', data).then(
      (loginCompiledTemplate) => {
        res.send(loginCompiledTemplate);
      }
    );

My handlebars service:

const handlebars = require('express-handlebars').create();

const getTemplate = async (path, data) => {
  const template = await handlebars
    .getTemplate(`./src/views/${path}.handlebars`)
    .catch((err) => {
      console.log(err);
    });
  return template(data);
};

module.exports = { getTemplate };

But when in my view I try to call "ifCond" it doesn't recognize it, because it gives me this error

{{#if campos }}
{{#each camposManuales}}
{{#ifCond this.field_type == 1 }}
  a
{{/ifCond}}
{{/each}}
{{/if}}

The error:

UnhandledPromiseRejectionWarning: Error: Parse error on line 14:
           .field_type == 1 }}

How can i fix this? What is wrong? Thank u so much!! ^^


Solution

  • You don't need to use your handlebarsService since you can use res.render function as shown bellow. The render function internaly does essentialy the same you do in the handlebarsService.

    const handlebars = require('express-handlebars');
    const server = express();
    
    var hbs = handlebars.create({
        helpers: {
            toJson: ...,
            ifCond: ...
        }
    });
    
    
    app.engine('handlebars', hbs.engine);
    app.set('view engine', 'handlebars');
    app.set('views', './views');
    
    app.get('/', (req, res) => {
        // there must be a home.html file in ./views folder
        res.render('home' /*, { some: 'data' }*/);
    });
    
    app.listen(3000);
    

    Note: The create function makes a new instance of handlebars so in order for your code to work, you would have to pass same options(helpers, etc.) to both instances.