javascript - 如何将函数传递给 nodejs-express 中的 express-handlebars?

标签 javascript node.js function express express-handlebars

我正在尝试在 express-handlebar 中传递一个函数, 但它不工作。 我使用 app.js 作为服务器文件,使用 index.handlebars 作为 Handlebars 文件。

应用程序.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>

最佳答案

最好为此创建一个助手。下面是一个例子并引用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>

关于javascript - 如何将函数传递给 nodejs-express 中的 express-handlebars?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/56399436/

相关文章:

javascript - 如何在 meteor 中使用非 npm node_module?

javascript - 是否存在用于将对象属性的子集复制到新对象中的 ES6 速记?

javascript - jQuery 插件创作 : Cannot get basic example to work?

javascript - nodejs + mqlight 连接错误

C++程序在函数调用处停止

javascript - Meteor 中独特的 Canvas

node.js - MongoDB watch() 使用 NodeJS 和 Mongoose 观察数据库中的变化

node.js - "describe"和 "schema.define"和有什么区别?

python - 这两个代码有什么区别?

c++ - 如何使用模板而不是宏来创建具有动态数量函数的类