Handle register Helper server with Expressjs

I use expressjs with rudders as templates for modeling using the following code in the Webstorm IDE with express generator. There are no visible descriptors in the code (I think the express generator has it somewhere else, which is not visible)

var app = express();
.
.    
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');

How do I use registerHelper on a server in this situation?

My other renderings and partial files work. So the helms do their job. It is this registerHelper that causes concern.

+2
source share
2 answers

I think it express-generatorjust installs view engineonly hbs. To configure the engine hbs, you must use express-handlebars.

eg.

var app = express(),
exphbs = require("express-handlebars");

app.engine("hbs", exphbs({
  defaultLayout: "main",
  extname: ".hbs",
  helpers: require("./public/js/helpers.js").helpers, // same file that gets used on our client
  partialsDir: "views/partials/", // same as default, I just like to be explicit
  layoutsDir: "views/layouts/" // same as default, I just like to be explicit
}));
app.set("view engine", "hbs");

helpers.js

var register = function(Handlebars) {
  var helpers = {
    // put all of your helpers inside this object
    foo: function(){
        return "FOO";
    },
    bar: function(){
        return "BAR";
    }
  };

  if (Handlebars && typeof Handlebars.registerHelper === "function") {
    // register helpers
    for (var prop in helpers) {
        Handlebars.registerHelper(prop, helpers[prop]);
    }
  } else {
      // just return helpers object if we can't register helpers here
      return helpers;
  }

};

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

: http://www.codyrushing.com/using-handlebars-helpers-on-both-client-and-server/

+5

@Mukesh Sharma, , .

, , . , ,

// index.js

//in the declarations
const exphbs  = require('express-handlebars');

//when configuring the app view engine
app.engine('.hbs', exphbs({
  extname: '.hbs',
  helpers: require('./config/handlebars-helpers') //only need this
}));
app.set('view engine', '.hbs');

, , .

// config/handlebars-helpers.js

module.exports = {
  ifeq: function(a, b, options){
    if (a === b) {
      return options.fn(this);
      }
    return options.inverse(this);
  },
  bar: function(){
    return "BAR!";
  }
}

handlebars-express - exhbs , hbs .

(Bonus ifeq - , , true. - :

class= "{{#ifeq thisUrl '/about'}} active {{/ifeq}}", "" ) https://gist.github.com/pheuter/3515945

0

Source: https://habr.com/ru/post/1608402/


All Articles