I'm trying to load this helper on my Express / Handlebars project, but, I can't manage to make it work...
Here is my app.js
var express = require('express'),
exphbs = require('express-handlebars');
var app = express();
app.engine('handlebars', exphbs({
defaultLayout: 'main',
helpers: require('handlebars-form-helpers').helpers
}));
app.set('view engine', 'handlebars');
app.get('/', function (req, res) {
res.render('home');
});
app.listen(3000);
And here is the page when I try to load it
Kind of new with Handlebars integration with Express, so, I can't manage to figure it out...
This should work:
var exphbs = require('express-handlebars'),
handlebars = require('handlebars'),
helpers = require('handlebars-form-helpers').register(handlebars);
var hbs = exphbs.create({
helpers: helpers,
defaultLayout: 'main'
});
app.engine('.hbs', hbs.engine);
app.set('view engine', '.hbs');
You can find more info here: https://github.com/ericf/express-handlebars/blob/master/examples/advanced/server.js
Related
I am facing some errors while integrating hbs and express in node js
content from layouts& partials are getting not loaded ,even though they are connected to
app.js , layout is loading when we move it into root of view.its not loading when its in a folder inside view.
When i move layouts.hbs to root it starts to load but partials are not loading since its inside a folder.(error:The partial my_partial could not be found)
when i googled about partial i found that hbs.registerPartial(path.join(__dirname, "/views/partials")); could be used but it showed an error that hbs.registerPartial is not a function.
so anyone please suggest me what to do
I expect solution for
How can i load default layout and partials by creating folders named layouts and partials respectively
-- views
-- partials
partial1.hbs
partial2.hbs
-- layouts
layout.hbs
app.js
error.hbs
//app.js
var createError = require('http-errors');
var express = require('express');
const hbs = require('express-handlebars');
var path = require('path');
var cookieParser = require('cookie-parser');
var logger = require('morgan');
var indexRouter = require('./routes/index');
var usersRouter = require('./routes/users');
var app = express();
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'hbs');
hbs.registerPartial(path.join(__dirname, "/views/partials"));
app.engine("hps", hbs.engine({ extname: "hbs", defaultLayout: "layout", layoutsDir: path.join(__dirname, 'views', "layout"), partialsDir: path.join(__dirname, 'views', "partials") }))
console.log(path.join(__dirname, 'views', "layout"))
app.use(logger('dev'));
app.use(express.json());
app.use(express.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
app.use('/', indexRouter);
app.use('/users', usersRouter);
// catch 404 and forward to error handler
app.use(function (req, res, next) {
next(createError(404));
});
// error handler
app.use(function (err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});
module.exports = app;
I am a newbie to use express and as a result am bungling my way through making this web app.
I have my routes in a different file called route.js inside a module.export, and I manage all this inside app.js and I want to be able to serve a HTML page and keep it in the module. I've done so using sendFile but it doesn't serve the CSS and JS as well. What can I do to fix this?
app.js
//setup
var express = require('express');
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var bodyParser = require('body-parser');
var index = require('./routes/index');
var users = require('./routes/users');
var app = express();
var port = process.env.PORT || 3000;
var mongoose = require('mongoose');
var flash = require('connect-flash');
var passport = require('passport');
var session = require('express-session');
var path = require('path');
//db
var configDB = require('./config/database.js');
mongoose.connect(configDB.url);
require('./config/passport')(passport);
// view engine setup
//app.set('views', path.join(__dirname, 'views'));
//app.set('view engine', 'jade');
app.set('view engine', 'ejs');
//routes
//app.use('/', index);
//app.use('/users', users);
// uncomment after placing your favicon in /public
//app.use(favicon(path.join(__dirname, 'public', 'favicon.ico')));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({ extended: false }));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
//passport
app.use(session({secret: 'secret'}));
app.use(passport.initialize());
app.use(passport.session());
app.use(flash());
//routes
require('./app/routes.js')(app, passport);
// catch 404 and forward to error handler
/*app.use(function(req, res, next) {
var err = new Error('Not Found');
err.status = 404;
next(err);
});*/
// error handler
/*app.use(function(err, req, res, next) {
// set locals, only providing error in development
res.locals.message = err.message;
res.locals.error = req.app.get('env') === 'development' ? err : {};
// render the error page
res.status(err.status || 500);
res.render('error');
});*/
module.exports = app;
//launch
app.listen(port);
console.log('Website starting on port ' + port);
routes.js
module.exports = function(app,passport) {
...
//--timesheet section---
app.get('/timesheet', function(req, res) {
var path = require('path');
res.sendFile(path.resolve('public/timesheet.html'));
});
...
}
You want to use a view engine and a static directory. You have some of the code already.
Your view engine using .ejs:
app.set('views', path.join(__dirname, 'views'));
app.set('view engine', 'ejs');
And you can define your static and specify a path prefix:
app.use('/assets', express.static(path.join(__dirname, 'public')));
In your views directory, put your htmls with .ejs extension, such as timesheet.ejs. You can then create an assets directory for your css/js/image files and reference them in your timesheet.ejs using /assets/style.css.
Finally, in your route, you'll want to render the template:
res.render('timesheet')
The common middle for expressjs is the Route() middleware, but now I'm dropping jade and using handlebars. Handlebars itself have it ways to define the route. Because of that I may mess up my controllers inside my app.js.
Below is my app.js, any idea how can I split the route to a new file?
var express = require('express');
var app = express();
var exphbs = require('express-handlebars');
app.engine('handlebars', exphbs({defaultLayout: 'main'}));
app.set('view engine', 'handlebars');
app.get('/',function(req,res){
res.render('index');
});
var port = Number(process.env.PORT || 3000);
app.listen(port);
Something like this?
//exported routes in ./routes/index.js
var routes = require('./routes');
//invoke routes
routes(app);
and routes file
module.exports = function(app) {
app.post('/etc', function(req,res) {
/* do route stuff */
});
/* other stuff goes here */
}
I'm trying work open page home of directory partials/home using ng-view and ng-view not working with express. A new page opens with render when acess http://localhost:3000/home. All routes defined for angular has no effect. I would like to know how to render my page partials/home.html in index.html using ng-view with express.
app.js
//módulos
var express = require('express');
var load = require('express-load');
var bodyParser = require('body-parser');
var app = express();
var path = require('path');
var favicon = require('serve-favicon');
var logger = require('morgan');
var cookieParser = require('cookie-parser');
var server = require('http').Server(app);
var io = require('socket.io')(server);
// view engine setup
app.set('views', path.join(__dirname, 'views'));
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
//uncomment after placing your favicon in /public
app.use(favicon(__dirname + '/public/favicon.ico'));
app.use(logger('dev'));
app.use(bodyParser.json());
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(cookieParser());
app.use(express.static(path.join(__dirname, 'public')));
load('routes').then('controllers').into(app);
server.listen(3000);
console.log('Site no ar ...');
module.exports = app;
Routes Express - index.js
module.exports = function (app) {
app.get('/', function(req, res){
res.render('index');
});
app.get('/:name', function(req, res){
var name = req.params.name;
res.render('partials/' + name);
});
app.get('*', function(req, res){
res.render('index');
});
};
Routes Angular - Location: public/app/app.js
var app = angular.module('appSiteFio',['ngRoute']);
app.config(function($routeProvider, $locationProvider){
// remove o # da url
$locationProvider.html5Mode(true);
$routeProvider
.when('/', {
templateUrl : 'index.html',
controller : 'mainController',
})
.when('/home', {
templateUrl : 'partials/home.html',
controller : 'homeController',
})
.otherwise ({ redirectTo: '/' });
});
I would suggest changing the index.js file to something like:
module.exports = function (app) {
app.use(express.static('/partials')); //here you can write your partials directory.
app.get('*', function(req, res){
res.render('index');
});
};
(Also change your templateUrl inside angular file with the partials prefix.);
that way angular will allways will be loaded and angular router will deal with all the views fetching from the static partials folder
i am creating a chat application using socket.io and angularjs, when i run the app.js file using cmd, i get an error saying "app.configure(function){} typeerror undefined is not a function"
what could be the problem?
my code looks like this:
var http = require('http');
var express = require('express'),
routes = require('./routes'),
socket = require('./routes/socket.js');
app = module.exports.app = express();
var server = http.createServer(app);
var io = require('socket.io').listen(server); //pass a http.Server instance
server.listen(80);
// Configuration
app.configure(function(){
app.set('views', __dirname + '/views');
app.set('view engine', 'jade');
app.set('view options', {
layout: false
});
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.static(__dirname + '/public'));
app.use(app.router);
});
i was using Express 4.0 in which configure was removed. See http://expressjs.com/guide/migrating-4.html#other-changes
Simple mistake took me an hour to realise.