Error: Missing Helper in Handlebars.js

≡放荡痞女 提交于 2019-12-04 03:32:23

I figured it out...The helpers indeed need to be registered in the node app file like so:

// view engine
app.set('views', __dirname + '/views/');
app.set('view engine', 'handlebars');
var hbs = require('handlebars');
hbs.registerHelper("inc", function(value, options)
{
    return parseInt(value) + 1;
});
app.engine('handlebars', engines.handlebars);

I wish this info was more easily accessible, but there it is.

Register a math handlebar and perform all mathematical operations.

app.engine('handlebars', exphbs({
  helpers:{
    // Function to do basic mathematical operation in handlebar
    math: function(lvalue, operator, rvalue) {lvalue = parseFloat(lvalue);
        rvalue = parseFloat(rvalue);
        return {
            "+": lvalue + rvalue,
            "-": lvalue - rvalue,
            "*": lvalue * rvalue,
            "/": lvalue / rvalue,
            "%": lvalue % rvalue
        }[operator];
    }
}}));
app.set('view engine', 'handlebars');

Then you can directly perform operation in your view.

    {{#each myArray}}
        <span>{{math @index "+" 1}}</span>
    {{/each}}

You could just paste the helpers inside a separate file, as you said something like "helper.js" and include it in your HTML page after you had imported Handlebars JS file.

<script src="handlebars.min.js"></script>
<script src="helper.js"></script>

You can also check out Swag (https://github.com/elving/swag) It contains a lot of helpful handlebar helpers.

You don't need to add require('handlebars') just to get helpers working. You can stick to express-handlebars. Define helpers in a config object like so var myConfig = { helpers: {x: function() {return "x";}} } and pass it to the express-handlebars-object like so: require('express-handlebars').create({myConfig})

Here's a fully functional example with some helpers and some view directories configured.

var express = require('express');
var exphbs = require('express-handlebars');
var app = express();
var hbs = exphbs.create({
    helpers: {
        test: function () { return "Lorem ipsum" },
        json: function (value, options) {
            return JSON.stringify(value);
        }
    },
    defaultLayout: 'main',
    partialsDir: ['views/partials/']
});
app.engine('handlebars', hbs.engine);
app.set('view engine', 'handlebars');
app.set('views', path.join(__dirname, 'views'));

My understanding is that the object returned from require('express-handlebars'); is not a "real" handlebars object. So you can't rely on some functions, and instead you have to pass stuff like helpers via a config object to the .create() function

A friend of mine suggested this as well, and it worked!

<h2>Success!</h2>
{{#each data}}
 <div>
    Name: {{ LocalizedName }}<br>
    Rank: {{ Rank }}<br>
 </div> 
 {{/each}}
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!