Handlebarsjs check if a string is equal to a value

后端 未结 13 802
挽巷
挽巷 2020-12-08 18:23

Is it possible in Handlebars to check if a string is equal to another value without registering a helper? I can\'t seem to find anything relevant to this in the Handlebars r

13条回答
  •  悲哀的现实
    2020-12-08 19:28

    You cannot directly compare the strings in handlebars and you have to use a helper. I tried the above solutions with my Koa app and couldn't register the helper. The below code worked for me and i think this should work for express apps as well. I hope this helps someone.

    Code in server.js

    var handlebars = require('koa-handlebars');
    
    const isEqualHelperHandlerbar = function(a, b, opts) {
                if (a == b) {
                    return opts.fn(this) 
                } else { 
                    return opts.inverse(this) 
                } 
            }
            
    app.use(handlebars({
        viewsDir: './app/views',
        layoutsDir: './app/views/layouts',
        defaultLayout: 'main',
        helpers : {
            if_equal : isEqualHelperHandlerbar
        }
    }));

    Code in HBS file where fruit is the variable to be compared:

     

提交回复
热议问题