2

I am trying to pass a function in express-handlebar, but it is not working. I am using app.js as server file and index.handlebars as handlebar file.

app.js

const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');
app.engine('handlebars', exphbs());
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

function hello(){
  console.log('hello');
}

app.get('/', function (req, res) {
    res.render('index',{
      hello:hello
    });
});

 app.listen(3000);

index.handlebars

<button onclick="hello()">click</button>
Nishant soni
  • 41
  • 3
  • 9
  • function hello is on the server side, your button is calling a function on the client side. Move function hello on the client side and provide whatever variables you need from the server. – Jabberwocky May 31 '19 at 17:30
  • Thanks @Jabberwocky but how to move it to client side ? – Nishant soni Jun 01 '19 at 02:32
  • This may help [html button onclick in Node.js](https://stackoverflow.com/questions/18831783/how-to-call-a-server-side-function-from-client-side-e-g-html-button-onclick-i) – AKSHAY SALEKAR Jun 01 '19 at 06:40

1 Answers1

0

Best to create a helper for this. Below an example and referring to Github for more info on the topic.

const express=require('express');
const app=express();
const csc=require('countrycitystatejson');
const exphbs=require('express-handlebars');

var hbs = exphbs.create({
    helpers: {
        hello: function () { console.log('hello'); }
    }
});

app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');

// console.log(csc.getAll());

app.get('/', function (req, res) {
    res.render('index');
});


app.listen(3000);

index.handlebars

<button onclick="{{hello}}">click</button>
Karel
  • 79
  • 1
  • 5
  • By this approach, I will have to register every passing function as a helper function. I don't think using this approach is good for big projects – Nishant soni Jun 05 '19 at 18:40
  • 1
    Hi, The above answer is correct according to their documentation: https://github.com/ericf/express-handlebars – Dan Nov 24 '19 at 03:35