How to use .html file extensions for handlebars in express?

自古美人都是妖i 提交于 2019-12-22 05:28:30

问题


So I was wondering how I could use .html extensions instead of .handlebars or .hbs extensions. I am doing this so I can develop using regular html so that my frontend developers can seamless edit files in their IDEs without any extra configuration. Plus it will help installing html templates much faster into our express applications.


回答1:


So I was able to do this by changing three things in my app.js file I hope this helps everyone out as much as it helped me!

var express  = require('express'),
    exphbr   = require('express3-handlebars'), // "express3-handlebars"
    helpers  = require('./lib/helpers'),

    app = express(), 
    handlebars;

// Create `ExpressHandlebars` instance with a default layout.
handlebars = exphbr.create({
    defaultLayout: 'main',
    helpers      : helpers,
    extname      : '.html', //set extension to .html so handlebars knows what to look for

    // Uses multiple partials dirs, templates in "shared/templates/" are shared
    // with the client-side of the app (see below).
    partialsDir: [
        'views/shared/',
        'views/partials/'
    ]
});

// Register `hbs` as our view engine using its bound `engine()` function.
// Set html in app.engine and app.set so express knows what extension to look for.
app.engine('html', handlebars.engine);
app.set('view engine', 'html');

// Seperate route.js file
require("./routes")(app, express);

app.listen(3000);



回答2:


Agree with JemiloII,

  1. extname: '.myext' in the config while creating the expr-HBS instance (exphbr.create()) according to https://www.npmjs.org/package/express3-handlebars#-extname-handlebars-
  2. binding the expr-HBS engine to the extension: app.engine('myext', handlebars.engine); according to http://expressjs.com/3x/api.html#app.engine
  3. set the extension as view engine: app.set('view engine', 'myext'); - unfortunately no link to how it works.

Regards



来源:https://stackoverflow.com/questions/22278014/how-to-use-html-file-extensions-for-handlebars-in-express

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!