Как передать функцию express-handlebars в nodejs-express? - PullRequest
2 голосов
/ 31 мая 2019

Я пытаюсь передать функцию в экспресс-руле, но она не работает.Я использую app.js в качестве файла сервера и index.handlebars в качестве файла handlebar.

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>

1 Ответ

0 голосов
/ 31 мая 2019

Лучше всего создать помощника для этого.Ниже приведен пример со ссылкой на Github для получения дополнительной информации по теме.

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>
...