How to make a #if with comparison of two variables using handlebars and nodejs

Asked

Viewed 177 times

2

My problem is in creating #if with a comparison with two variables on the .handlebars. page In the edition page I retrieve the data and fill in the fields, however in my select, I need to compare the current id with the ids from the select list, to disable and mark as selected the option that contains the category of the current post I am editing but this comparison does not seem to be allowed this way.

<select name="categoria" id="categoria" class="form-select">
        {{#each categorias}}
                    
             //esse if nao funciona
             {{#if _id == postagem.categoria._id}}
                    <option value="{{postagem.categoria._id}}" selected="true" disabled>
             {{else}}
                    <option value="{{_id}}">{{nome}}</option>
             {{/if}}
        {{else}}
             <option value="0">Nenhuma categoria</option>
        {{/each}}
</select>

That’s the result I want inserir a descrição da imagem aqui

  • friend, managed to do what you needed, using my answer? If you need anything else, comment! I hope to have helped.

  • continues the problem Error: Parse error on line 24:&#xA;... {{#if _id == postagem.categoria&#xA;-----------------------^&#xA;Expecting 'OPEN_SEXPR', 'ID', 'STRING', 'NUMBER', 'BOOLEAN', 'UNDEFINED', 'NULL', 'DATA', got 'EQUALS'

  • Ué continues the problem because you haven’t changed the code! Vc need to create a helper and use it! Vc understood what handlebars helpers are for?

  • I created the helper ifCompare: function (a, b, options) {if (a == b) { return options.fn(this); } return options.inverse(this);} Apparently it’s working fine

1 answer

2


Register the helper you need and use it. Here’s an example of several helpers I have.

var register = function(Handlebars) {
    var helpers = {
        isSinglePrice: function(arr, options) {
            if(arr.length === 1) {
                return options.fn(this);
            }else{
                return options.inverse(this);
            }
        },
        choosePriceIcon: function(position){
            if(position === 0){
                return "person";
            }else if(position === 1){
                return "group";
            }else if(position === 2){
                return "groups";
            }
        },
        numberFormat: function (value, options) {
            // Helper parameters
            var dl = options.hash['decimalLength'] || 2;
            var ts = options.hash['thousandsSep'] || ',';
            var ds = options.hash['decimalSep'] || '.';

            // Parse to float
            var value = parseFloat(value);

            // The regex
            var re = '\\d(?=(\\d{3})+' + (dl > 0 ? '\\D' : '$') + ')';

            // Formats the number with the decimals
            var num = value.toFixed(Math.max(0, ~~dl));

            // Returns the formatted number
            return (ds ? num.replace('.', ds) : num).replace(new RegExp(re, 'g'), '$&' + ts);
        }
    };

    if (Handlebars && typeof Handlebars.registerHelper === "function") {
        for (var prop in helpers) {
            Handlebars.registerHelper(prop, helpers[prop]);
        }
    } else {
        return helpers;
    }

};

module.exports.register = register;
module.exports.helpers = register(null);

Just create as many helper methods as you need to make the comparisons you need and use it the way you think best.

And here as you use:

var exphbs = require('express-handlebars');

var handlebars = exphbs.create({
    layoutsDir: path.join(__dirname, "views/layouts"),
    partialsDir: path.join(__dirname, "views/partials"),
    defaultLayout: 'index',
    extname: 'hbs',
    helpers: require("./helpers/hbs.js").helpers
});

EDIT: Here is an example of how you assign the handlebars engine, with the helpers registered above:

const app = express();
app.engine('hbs', handlebars.engine);
app.set('view engine', 'hbs');
app.set('views', './views')

Now it’s up to you. I hope I’ve helped.

  • Without this helper the express is informed about the handlebars in this way app.engine('handlebars', handlebars({defaultLayout: 'main'}));. How to tell express to use handlebars in this case?

  • @Bernardolopes added how you should do for your express app to use. Stay tuned with the issue of layouts, if you do not inform the right directory, for example: views/layouts and views/partials will not work correctly Engine.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.