ericf / express-handlebars

A Handlebars view engine for Express which doesn't suck.
BSD 3-Clause "New" or "Revised" License
2.31k stars 384 forks source link

how to use comparison operators? Its not working. #222

Open kumaryogidev opened 6 years ago

kumaryogidev commented 6 years ago
screen shot 2018-01-23 at 8 09 36 pm
stoberov commented 6 years ago

It is possible to register custom helpers, as described here: https://stackoverflow.com/questions/8853396/logical-operator-in-a-handlebars-js-if-conditional

Just add your custom helper functions when setting up the exphbs engine in your app. Personally, I'm a little divided which is the less of two evils - to add the compare functionality manually so it can be used in the view (against the Handlebars philosophy) or to pass the already-compared-variables to the view (more work).

knoxcard commented 6 years ago

app.js

var  express = require('express'),
  app = express()
  app.engine('.hbs', require('express-handlebars')({
    defaultLayout: '',
    extname: '.hbs',
    helpers: require(require('path').join(__dirname, 'lib/helpers.js')).helpers,
    layoutsDir: require('path').join(__dirname, 'templates/layouts'),
    partialsDir: __dirname + '/templates/partials'
  }))

/lib/helpers.js

var register = Handlebars => {
  var helpers = {
    if_eq: function(a, b, opts) {
        return a == b ? opts.fn(this) : opts.inverse(this)
    },
    if_neq: function(a, b, opts) {
      return a == b ? opts.inverse(this) : opts.fn(this)
    },
    if_null: function(a, opts) {
      return typeof(a) === 'undefined' ? opts.fn(true) : opts.inverse(false)
    },
    if_not_null: function(a, opts) {
      return typeof(a) === 'undefined' ? opts.inverse(false) : opts.fn(true)
    },
    if_not_includes: function(a, b, opts) {
      return opts.fn(!a.includes(b))
    },
    select: function(selected, options) {
      return options.fn(this).replace(new RegExp(' value=\"' + selected + '\"'), '$& selected="selected"').replace(new RegExp('>' + selected + '</option>'), ' selected="selected"$&')
    },
    capitalizeFirst: function(str) {
      return str.charAt(0).toUpperCase() + str.slice(1)
    },
    if_contains: function(array, value, opts) {
      if(array)
        return (array.includes(value)) ? opts.fn(this) : opts.inverse(this)
      return ''
    },
    capitalizeEveryFirst: function(str) {
      str = str.toLowerCase().split(' ')
      for(var i = 0; i < str.length; i++) 
        str[i] = str[i].charAt(0).toUpperCase() + str[i].slice(1)
      return str.join(' ')
    },
    json: function(obj) {
      return JSON.stringify(obj)
    }
  }
  if(Handlebars && typeof Handlebars.registerHelper === 'function')
    for(var prop in helpers)
      Handlebars.registerHelper(prop, helpers[prop])
  return helpers
}
module.exports.register = register
module.exports.helpers = register(null)
vinyoliver commented 5 years ago

Tks @knoxcard :)