How to set title in ejs template? - node.js

I tried setting title using
app.set('title', 'My Site');
And in the ejs temlplate, I tried using it.
<h1 class="logo"><%= title %><span>.</span></h1>
But, getting below error.
title is not defined
at eval (eval at compile (D:\crypto_assets\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:12:26)
at header (D:\crypto_assets\node_modules\ejs\lib\ejs.js:692:17)
at include (D:\crypto_assets\node_modules\ejs\lib\ejs.js:690:39)
at eval (eval at compile (D:\crypto_assets\node_modules\ejs\lib\ejs.js:662:12), <anonymous>:18:17)
at portfolio (D:\crypto_assets\node_modules\ejs\lib\ejs.js:692:17)
at tryHandleCache (D:\crypto_assets\node_modules\ejs\lib\ejs.js:272:36)
at View.exports.renderFile [as engine] (D:\crypto_assets\node_modules\ejs\lib\ejs.js:489:10)
at View.render (D:\crypto_assets\node_modules\express\lib\view.js:135:8)
at tryRender (D:\crypto_assets\node_modules\express\lib\application.js:640:10)
at Function.render (D:\crypto_assets\node_modules\express\lib\application.js:592:3)

app.set() is used to define a setting against the name with its value e.g. app.set('foo', 'bar') set the foovalue tobar. To access the setting value, you need to use app.get()method asapp.get('foo'). You can't just access it via name in app.js` (or any other) file and in templates.
As mentioned in comment, you need to pass object as title property from where you're rendering the the view.
router.get("/", function (req, res, next) {
res.render("index", { title: "Express" });
});
In case, if you're looking for a variable that you can use throughout all the templates, can define it using res.locals property in middleware such as,
app.use(function (req, res, next) {
res.locals.title = "Marker";
next();
});
With this, you can now use the title in view.

Related

How to access the variable passed through res.renderer?

I'm passing a variable to my template renderer in ExpressJs like so:
index.js
app.get('/simple_view/', function(req, res, next){
title='A TITLE';
res.render('simple', {
title: title
});
});
I would like to access the title variable in a JS script on my template page, but I'm getting Uncaught ReferenceError: title is not defined error.
simple.pug
script.
console.log(title);
How can I solve this?
The Getting Started for PUG already showcases how to embed variables. You do this by using #{variable_name}, e.g. #{title} in your case.

Get name of template inside a pugjs template

I'm rendering my pages with pugJS like this:
res.render('test',renderVars)
This render uses a layout, in which I need to get the 'test' string. My question is: how can I get the 'test' string so that I can use it in my layout? I could put a new variable in 'renderVars' but I'm sure there is a better solution.
In other words: how can I get the name of a template inside this template? Something like #{templatename} for example?
Thanks in advance!
I'm afraid you can't do so. res.render 1st parameter is rendering a view template not mean to store data. You could set the 'test' in renderVars or you can add it in session and will be able to use it in your layout.
Add this code into your app.js before the routes and after session settings
//inject session into res.locals so can be rendered in UI
app.use(function (req, res, next) {
if (req.session.message) {
res.locals.message = req.session.message;
delete req.session.message;
}
res.locals.session = req.session;
next();
});
In the view template you can access the res.locals.session data by using
#{session.theAttributeYouWant)

Kraken.js dust view engine

I am using Kraken.js with Dust as the default view engine. I get this error:
No default engine was specified and no extension was provided. at
new View
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/view.js:62:11)
at EventEmitter.render
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/application.js:569:12)
at ServerResponse.render
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/response.js:961:7)
at /home/zhiro/Desktop/kraken/krakil/controllers/index.js:14:13 at
Layer.handle [as handle_request]
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/layer.js:95:5)
at next
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/route.js:131:13)
at Route.dispatch
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/route.js:112:3)
at Layer.handle [as handle_request]
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/layer.js:95:5)
at
/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/index.js:277:22
at Function.process_params
(/home/zhiro/Desktop/kraken/krakil/node_modules/express/lib/router/index.js:330:12)
I see this error when I call res.render.
'use strict';
var IndexModel = require('../models/index');
module.exports = function (router) {
var model = new IndexModel();
router.get('/', function (req, res) {
res.render('index');
});
};
By default, Kraken doesn't configure a default view engine. The view engine tells Express how it should attempt to render files if it doesn't have a renderer explicitly defined for that file extension.
When you configure a new project using yo kraken, one of the questions it asks is what you would like your default view engine to be, but it sounds like you chose None on that step.
To set the default view engine, you simply pass it as part of the config object when instantiating Kraken. You can read about this in the Kraken README, under the heading Configuration-Based Express Settings:
Set the view engine property to the one of the view engines property names (see the section View Engine Configuration) to enable it for template rendering.
{
"express": {
[...]
"view engine": null, // set this to "dust"
[...]
}
}

res.render('index.html', {layout : null}) generating error

following demo project Here and blog post Here.
He is using jade engine which I don't want to use instead using Angularjs templating and routing.
Root folder is
client > js (contain all js files)
> views > partials > html files
> index.html
After changes in his code I am stuck with the below code
I am unable to send proper response.
if I use res.render('index.html', {layout : null}); than get error when refresh page
ERROR :
Error: Cannot find module 'html'
at Function.Module._resolveFilename (module.js:338:15)
at Function.Module._load (module.js:280:25)
at Module.require (module.js:364:17)
at require (module.js:380:17)
if I use res.redirect('/') than refresh the page always send me root (/) defined in app.js.
Needed : I want to send response or not to be on the same page even if I refresh the browser.
{
path: '/*',
httpMethod: 'GET',
middleware: [function(req, res) {
var role = userRoles.public, username = '';
if(req.user) {
role = req.user.role;
username = req.user.username;
}
res.cookie('user', JSON.stringify({
'username': username,
'role': role
}));
//res.render('index.html', {layout : null});
//res.redirect('/');
}],
accessLevel: accessLevels.public
}
If you're not using a backend template language (like jade), then you want to use res.sendfile instead of res.render. Render will look for a template engine matching the extension of the file (such as .jade) and then run the file through it. In this case, it assumes there must be a rendering engine called html, but there is not. SendFile will simply transfer the file as-is with the appropriate headers.
EDIT:
I'm still not 100% sure what you're asking, but I think what you're saying is you want your wildcard route to redirect people to the homepage if they aren't logged in, but if they are, then let other routes take over.
If that is the case you just need to put in a check in your "middleware" function for the /* route.
Instead of:
function(req, res) {
res.redirect('/');
}
Use some type of conditional logic:
function (req, res, next) {
if (/* !req.cookie.something or whatever */)
res.redirect('/');
else
next(); // continue on to the next applicable (matching) route handler
}
That way you won't always get caught in the redirect loop. Obviously, the above conditional logic could be asynchronous if necessary.
I still believe res.sendfile is the correct answer to the other portion of your question, just as the github members also suggested.

Express.js Middleware - Adding items to the response object model

I'm playing around with Expressjs and am attempting to extract the page title from the default template to middleware instead of passed into the view's model each time.
Default index.jade template
h1= title
p Welcome to the #{title}
Default route from template
exports.index = function(req, res){
res.render('index', { title: "Express" });
};
I attempted the following but get an error from Express saying title is undefined when I do this.
module.exports = function(req, res, next){
res.title = 'Express';
next();
}
This is obviously a trivial example but it's also something that I am trying to figure out since there will probably come a time where I want to inject things into the response's model after each route. I just cannot figure out how to do such.
Thanks
You have to use default helpers. Read the documentation. Here's a simple snippet:
app.helpers({
title: 'Express'
});
/* Now JADE sees your variable title
without explicitly defining it
in every view. */
Also look at dynamic helpers in the documentation. These can be linked to req and res variables (normal helpers do not depend on request/response).

Resources