Handlebarsjs check if a string is equal to a value

后端 未结 13 763
挽巷
挽巷 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:

     <select id={{fruit}}>
       <option >Choose...</option>
       <option value="apple" {{#if_equal fruit "apple"}} selected {{/if_equal}}>Apple</option>
       <option value="mango" {{#if_equal fruit "mango"}} selected {{/if_equal}} >Mango</option>
     </select>

    0 讨论(0)
提交回复
热议问题