Issues with rendering handlebars views in nodejs express - node.js

I am facing an issue, that res.render does not render index view. View engine works, because I see that default layout is loaded, maybe some had same issue?
index.js
var hbs = exphbs.create({
extname: '.hbs',
defaultLayout: 'default',
helpers: "./lib/templates/helpers",
partialsDir:"./lib/templates/partials",
layoutsDir:"./lib/templates/layouts"
});
app.engine('hbs', hbs.engine);
app.set('views', Path.join(__dirname, '/templates'));
app.set('view engine', 'hbs');
app.use('/', (req, res, next) => {
LandRoutes(app, req, res);
next();
})
register.js
const landRoutes = (app, req, res) => {
app.get("/", (req, res) => {
return res.render("index")
})
}
default.hbs
<!DOCTYPE html>
<html lang="en-US">
<head>
{{> head }}
</head>
<div id="main">
{{{content}}}
</div>
</html>
index.hbs
<div id="root">
<div class="loader-wrapper">
<div class="loader"></div>
</div>
</div>
file structure:
lib/templates
/helpers
/layouts/default.hbs
/partials
/index.hbs
Thanks in an advance!

Related

Where to put Handlebars.registerHelper function in node.js project?

I want to increase "totalPrice" by 10 and then display it in handlebars templates . Here z some snippet of my handlebar file.
checkout.hbs
<ul class="shipping__method">
<li>Shipping <span>$ 10</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
For that i write this in my app.js file
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
expressHbs.registerHelper ('increasePrice', function (price) {
price+=10;
return price;
})
And then i got error expressHbs.registerHelper is not a function. Then i came to know to write it like this
var hbs = expressHbs.create({
helpers: {
increasePrice: function(price) {
price+=20;
return price;
}
}
})
And then i got error like "missing Helper: "increasePrice" ".
👨‍🏫 You see this code below 👇, an example code using express and express-handlebars:
index.js
var express = require('express');
var app = express();
var expressHbs = require('express-handlebars');
app.engine('.hbs', expressHbs({ defaultLayout: 'layout', extname: '.hbs'}))
app.set('view engine', '.hbs');
var hbs = expressHbs.create({});
// register new function
hbs.handlebars.registerHelper('increasePrice', function(price) {
price+=10;
return price;
})
app.get('/', (req, res) => {
res.render('home', {
layout: false,
totalPrice: 300,
});
})
app.listen(3000, () => {
console.log('Server is up');
});
Now create file home.hbs in views, and put this code below 👇 in there.
home.hbs
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>My Example APP</title>
</head>
<body>
<ul class="shipping__method">
<li>Shipping: Total Price <span>$ {{ totalPrice }}</span></li>
</ul>
<ul class="total__amount">
<li>Order Total <span>Rs. {{increasePrice totalPrice}}</span></li>
</ul>
</body>
</html>
From the code above 👆, I hope you can understand now, where you have to put your function.
For an example: You can see on my codesandbox
I hope it's can help you 🙏.

Not being able to pass a variable from Express to EJS

I can't figure out where I messed up. When I try to render this in my browser it simply says.
ReferenceError: /views/login.ejs:14
12| <h1>
13| Value:
>> 14| <span id="val"><%= val %></span>
15| </h1>
16| </body>
17|
val is not defined
App.js (Relevant Stuff, I have Express required)
app.set('view engine', 'ejs');
app.set('views', path.join(__dirname + '/views'));
app.use(express.static(path.join(__dirname + '/public')));
app.use(bodyParser.urlencoded({
extended: false
}));
app.use(bodyParser.json());
app.use(session({
secret: 'hello world',
resave: true,
saveUninitialized: true
}));
app.get('/register', routes.register);
app.post('/register', routes.postRegister);
app.get('/login', function(req, res) {
res.render('login', {
val: 'whatever'
})
});
views/login.ejs
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>Login Page</title>
</head>
<body>
<h1>
Value:
<span id="val"><%= val %></span>
</h1>
</body>
</html>
I've been stuck in this simple problem for over an hour and honestly I have absolutely no idea what it means.
Everything seems ok with the code. Probably you forgot something trivial.
This is my working setup:
var express = require('express');
// Create a new Express application.
var app = express();
// Configure view engine to render EJS templates.
app.set('views', __dirname + '/views');
app.set('view engine', 'ejs');
// Define routes.
app.get('/', function(req, res) {
res.render('index', {
val: 'whatever'
});
});
app.listen(process.env.PORT || 5000);
console.log("Server running at http://localhost:5000/");

Express.js index.js 404 (Not Found)

For some reason it can't load my index.js script that is being referenced from my index.html. server.js, index.html, and index.js are all located at the root of my project folder.
server.js
var express = require('express'),
app = express();
app.set("view options", {layout: false});
app.use(express.static(__dirname + '/public'));
app.set('views', __dirname + '/');
app.engine('html', require('ejs').renderFile);
app.set('view engine', 'html');
app.get('/', function (req, res) {
res.render('index.html');
});
app.listen(4000, function () {
console.log('Example app listening on port 4000!');
});
index.html
<html>
</head></head>
<body>
<div class="ink-grid vertical-space">
<div id="content">
<div class="panel vertical-space">
<div id="app"/>
</div>
</div>
</div>
<script type="text/babel" src="index.js"></script>
</body>
</html>
You have to serve those files. You could do them individually:
app.get('/index.js', function (req, res) {
res.sendFile('index.js');
});
Or create a directory (e.g. www) for everything you want to serve and use express.static:
app.use(express.static('www'));
By looking declaration
app.use(express.static(__dirname + '/public'));
Your index.js file should be in the public directory.
Since index.js and server.js are in the same directory, define
app.use(express.static(.));

Dynamic partial in handlebars

The below code working fine but routes / and /signup will show same thing (except title) because the first argument in the res.render doesn't do anything and because in the layout I have {{< index}} which render the view with the name index. What I want is to dynamically pass the partial that I want to render (basically I want the first argument of res.render to have effect).
app.js
/* Variable declarations */
var express = require('express'),
hbs = require('hbs'),
app = express();
/* Setttings */
app.set('views', __dirname + '/views');
app.set('view engine', 'hbs');
app.set('view options', { layout: 'layout' });
/* Register Partials */
hbs.registerPartials(__dirname + '/views');
/* Routes */
app.get('/signup', function (req, res) {
res.render('index', {title: 'Welcome'});
});
app.get('/signup', function (req, res) {
res.render('signup', {title: 'Sign Up'});
});
/* Listeners */
app.listen(80, function () {
console.log('App started...');
});
Layout.hbs
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{> index}}
</body>
</html>
As part of Handlerbars 3.0 dynamic partials are included. You can find the reference here. With this new syntax the name of the partial is evaluated and dynamically replaced. I'm using "express-handlebars": "2.0.1",.
Layout.hbs
<!DOCTYPE html>
<html>
<head>
<title>{{title}}</title>
</head>
<body>
{{> (whichPartial) }}
</body>
</html>
App.js
/* Routes */
app.get('/', function (req, res) {
res.render('index', {title: 'Welcome'
whichPartial: function() {
return "thePartialNameForIndex";
}
});
});
app.get('/signup', function (req, res) {
res.render('signup', {title: 'Sign Up'
whichPartial: function() {
return "thePartialNameForSignup";
}
});
});
Where thePartialNameForIndex and thePartialNameForSignup are the name of the partials allocated in /views.

Angular.js and Express: Routing is not working

I've scoured the internet for somebody with a similar problem, but still no solutions. In comparing my app to Angular-Express-seed, Angular-Express-Master, and any of the other popular examples out there, nothing appears to be broken, yet it just doesn't work. Does anybody have a ideas of why this may be?
I'll try to spare detail without removing what may be the problematic bit of code:
/app.js
// All environments
app.set('views', __dirname + '/views');
app.set('port', process.env.PORT || 3000);
app.engine('.html', require('ejs').renderFile);
app.set('view engine', 'html');
app.set("view options", { layout: false });
app.use(express.favicon());
app.use(express.logger('dev'));
app.use(express.bodyParser());
app.use(express.methodOverride());
app.use(express.cookieParser());
app.use(express.session(
{ secret: 'spunkydelicious',
cookie : {
maxAge: (3600000*24*7) // 1 week
}
}
));
app.use(passport.initialize());
app.use(passport.session());
app.use(require('express-jquery')('/jquery.js'));
app.use(express.static(path.join(__dirname, '/public')));
app.use(app.router);
...
app.get('/', index.index);
app.get('/partials/:name', index.partials);
app.get('*', index.index);
where the 'index' of index.index, index.partials, etc. corresponds to this:
/app/controllers/index.js
exports.index = function(req, res){
res.render('index');
};
exports.partials = function(req, res) {
var name = req.params.name;
console.log('Hurah!');
res.render('partials/' + name);
};
/public/javascripts/app.js
'use strict';
// Declare app level module which depends on filters, and services
angular.module('emit', []).
config(['$routeProvider', '$locationProvider', function($routeProvider, $locationProvider) {
$routeProvider.when( '/', {
templateURL:'partials/test',
controller: AppCtrl
}).
otherwise({
redirectTo: '/'
});
$locationProvider.html5Mode(true);
}]);
/public/javascripts/controllers.js
'use strict';
/* Controllers */
function AppCtrl($scope) {
console.log('123');
}
/views/index.html
<!DOCTYPE html>
<html ng-app="emit">
<head>
<base href="/">
<link rel='stylesheet' href='/stylesheets/style.css' />
</head>
<body>
<div ng-view></div>
<!-- Plugins -->
<script src="/javascripts/vendor/angular/angular.js"></script>
<!-- Angular -->
<script src="/javascripts/app.js"></script>
<script src="/javascripts/controllers.js"></script>
<!-- Other scripts -->
**strong text** <script src="/javascripts/script.js"></script>
</body>
</html>
/views/partials/test.html
<div class="">Yay!</div>
Pardon the length of the code, I just can't crack what I'm doing wrong. No errors are logged by the server of the client console. Any debugging steps I could take?
After very long and confusing debug session I've figured this out... Surprisingly, the error is in templateURL - it should be templateUrl.

Resources