How to access the variable passed through res.renderer? - node.js

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.

Related

How do I access bashrc environment variables in pug script. section

I have a recaptcha site key stored in .bashrc and would like to use the environment variables in my pug view. The captcha section of my JS script is under a "script." section in the pug file.
I have attempted to use #{ } to interpolate the pug JS variable, and I have passed in the env variables through the 'route', but to no avail. The interpolation leaves an empty space in the captcha request.
// INDEX ROUTE
var express = require('express');
var router = express.Router();
const request = require('request');
var textUtil = require('../utils/sendText');
router.get('/', function(req, res, next) {
res.render('index', { title: 'Phoenix Flight Fire Supply', siteKey: process.env.PHOENIX_CAPTCHA_SITE_KEY }); // Passing in 'siteKey'
});
//INDEX PUG FILE
doctype html
html
head
title= title
script(async, src='https://www.googletagmanager.com/gtag/js?id=UA-144999292-1')
script.
window.dataLayer = window.dataLayer || [];
function gtag(){dataLayer.push(arguments);}
gtag('js', new Date());
gtag('config', 'UA-144999292-1');
meta(name='viewport' content='width=device-width, initial-scale=1')
meta(name='theme-color' content='#B61919')
link(rel='stylesheet', href='/stylesheets/style.css')
link(rel='stylesheet', href='/stylesheets/flickity.min.css' media='screen')
link(rel='icon' sizes='192x192' href='images/phoenixfirelogosolid.png')
script(src='javascripts/flickity.pkgd.min.js')
script(src='javascripts/libs/inflate.min.js')
script(src='https://cdnjs.cloudflare.com/ajax/libs/babylonjs/4.0.3/babylon.max.js')
script(src='https://d3js.org/d3.v3.min.js' language='JavaScript')
script(src='javascripts/liquidFillGauge.js' language='JavaScript')
script(src=`https://www.google.com/recaptcha/api.js?render=${siteKey}`)
link(rel='stylesheet' href='https://use.typekit.net/gmu0vhj.css')
link(rel='stylesheet' href='https://use.typekit.net/gmu0vhj.css')
link(rel='stylesheet' href='https://use.typekit.net/gmu0vhj.css')
body
block content
... (BODY)
script.
//RECAPTCA v3 LOAD
grecaptcha.ready(function() {
grecaptcha.execute(siteKey, {action: 'submitLead'}).then(function(token){
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});
While I am not getting any errors, recaptcha is not working properly because the siteKey is 'undefined'. Essentially, the pug preprocessing is not working correctly.
The preprocessing is not recognizing 'siteKey'. If I add #{}, the value is '' and recaptcha doesn't show.
grecaptcha.ready(function() {
grecaptcha.execute(siteKey, {action: 'submitLead'}).then(function(token) {
// add token value to form
document.getElementById('g-recaptcha-response').value = token;
});
});</script></body></html>
One last note: I check the .bashrc file, and the environment variable is spelled correctly. The key is surrounded by "" quotes, and I am running an Ubuntu 18.04 environment running Nginx as a proxy to Express.
Thank you for any help!
In your client-side JavaScript, I don't think you ever declared your siteKey variable.
Can you try something like this?
script(src=`https://www.google.com/recaptcha/api.js?render=#{siteKey}`)
...
script.
const siteKey = #{siteKey}
//RECAPTCA v3 LOAD
grecaptcha.ready(function() {
grecaptcha.execute(siteKey, ...
If that doesn't work, I'd first try to manually copy the key into the constant, and see if the application works.

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)

Send data along with html file using res.render() in express.js/node.js

How to access variable "name" in index.html file using res.render?
app.get("/", function(req, res){
res.render('index.html',{name: "xyz"});
});
Following is the example of codeigniter, I want to achieve same in node.js:
$data["name"] = "xyz"
$this->load->view("index", $data);
I can access "name" using $name in index.html while working in codeigniter. How to access the "name" variable in index.html while using node.js?
The problem is that you need to use something like $ npm install pug --save for that. Then you can make a 'Pug template file named index.pug in the views directory' (or in the directory of your existing index.html file) This template should contain the following:
html
head
title= title
body
h1= name
Then in your nodeJS file you can use res.render like this:
app.get('/', function (req, res) {
res.render('index', { name: 'xyz' })
})
Here are the docs I used (from the comment) https://expressjs.com/en/guide/using-template-engines.html
Hope this helps!

How to create global variables accessible in all views using Express / Node.JS?

Ok, so I have built a blog using Jekyll and you can define variables in a file _config.yml which are accessible in all of the templates/layouts. I am currently using Node.JS / Express with EJS templates and ejs-locals (for partials/layouts. I am looking to do something similar to the global variables like site.title that are found in _config.yml if anyone is familiar with Jekyll. I have variables like the site's title, (rather than page title), author/company name, which stay the same on all of my pages.
Here is an example of what I am currently doing.:
exports.index = function(req, res){
res.render('index', {
siteTitle: 'My Website Title',
pageTitle: 'The Root Splash Page',
author: 'Cory Gross',
description: 'My app description',
indexSpecificData: someData
});
};
exports.home = function (req, res) {
res.render('home', {
siteTitle: 'My Website Title',
pageTitle: 'The Home Page',
author: 'Cory Gross',
description: 'My app description',
homeSpecificData: someOtherData
});
};
I would like to be able to define variables like my site's title, description, author, etc in one place and have them accessible in my layouts/templates through EJS without having to pass them as options to each call to res.render. Is there a way to do this and still allow me to pass in other variables specific to each page?
After having a chance to study the Express 3 API Reference a bit more I discovered what I was looking for. Specifically the entries for app.locals and then a bit farther down res.locals held the answers I needed.
I discovered for myself that the function app.locals takes an object and stores all of its properties as global variables scoped to the application. These globals are passed as local variables to each view. The function res.locals, however, is scoped to the request and thus, response local variables are accessible only to the view(s) rendered during that particular request/response.
So for my case in my app.js what I did was add:
app.locals({
site: {
title: 'ExpressBootstrapEJS',
description: 'A boilerplate for a simple web application with a Node.JS and Express backend, with an EJS template with using Twitter Bootstrap.'
},
author: {
name: 'Cory Gross',
contact: 'CoryG89#gmail.com'
}
});
Then all of these variables are accessible in my views as site.title, site.description, author.name, author.contact.
I could also define local variables for each response to a request with res.locals, or simply pass variables like the page's title in as the optionsparameter in the render call.
EDIT: This method will not allow you to use these locals in your middleware. I actually did run into this as Pickels suggests in the comment below. In this case you will need to create a middleware function as such in his alternative (and appreciated) answer. Your middleware function will need to add them to res.locals for each response and then call next. This middleware function will need to be placed above any other middleware which needs to use these locals.
EDIT: Another difference between declaring locals via app.locals and res.locals is that with app.locals the variables are set a single time and persist throughout the life of the application. When you set locals with res.locals in your middleware, these are set everytime you get a request. You should basically prefer setting globals via app.locals unless the value depends on the request req variable passed into the middleware. If the value doesn't change then it will be more efficient for it to be set just once in app.locals.
You can do this by adding them to the locals object in a general middleware.
app.use(function (req, res, next) {
res.locals = {
siteTitle: "My Website's Title",
pageTitle: "The Home Page",
author: "Cory Gross",
description: "My app's description",
};
next();
});
Locals is also a function which will extend the locals object rather than overwriting it. So the following works as well
res.locals({
siteTitle: "My Website's Title",
pageTitle: "The Home Page",
author: "Cory Gross",
description: "My app's description",
});
Full example
var app = express();
var middleware = {
render: function (view) {
return function (req, res, next) {
res.render(view);
}
},
globalLocals: function (req, res, next) {
res.locals({
siteTitle: "My Website's Title",
pageTitle: "The Root Splash Page",
author: "Cory Gross",
description: "My app's description",
});
next();
},
index: function (req, res, next) {
res.locals({
indexSpecificData: someData
});
next();
}
};
app.use(middleware.globalLocals);
app.get('/', middleware.index, middleware.render('home'));
app.get('/products', middleware.products, middleware.render('products'));
I also added a generic render middleware. This way you don't have to add res.render to each route which means you have better code reuse. Once you go down the reusable middleware route you'll notice you will have lots of building blocks which will speed up development tremendously.
For Express 4.0 I found that using application level variables works a little differently & Cory's answer did not work for me.
From the docs: http://expressjs.com/en/api.html#app.locals
I found that you could declare a global variable for the app in
app.locals
e.g
app.locals.baseUrl = "http://www.google.com"
And then in your application you can access these variables & in your express middleware you can access them in the req object as
req.app.locals.baseUrl
e.g.
console.log(req.app.locals.baseUrl)
//prints out http://www.google.com
In your app.js you need add something like this
global.myvar = 100;
Now, in all your files you want use this variable, you can just access it as myvar
One way to do this by updating the app.locals variable for that app in app.js
Set via following
var app = express();
app.locals.appName = "DRC on FHIR";
Get / Access
app.listen(3000, function () {
console.log('[' + app.locals.appName + '] => app listening on port 3001!');
});
Elaborating with a screenshot from #RamRovi example with slight enhancement.
you can also use "global"
Example:
declare like this :
app.use(function(req,res,next){
global.site_url = req.headers.host; // hostname = 'localhost:8080'
next();
});
Use like this:
in any views or ejs file
<%
console.log(site_url);
%>
in js files
console.log(site_url);
With the differents answers, I implemented this code to use an external file JSON loaded in "app.locals"
Parameters
{
"web": {
"title" : "Le titre de ma Page",
"cssFile" : "20200608_1018.css"
}
}
Application
var express = require('express');
var appli = express();
var serveur = require('http').Server(appli);
var myParams = require('./include/my_params.json');
var myFonctions = require('./include/my_fonctions.js');
appli.locals = myParams;
EJS Page
<!DOCTYPE html>
<html lang="fr">
<head>
<meta charset="UTF-8">
<title><%= web.title %></title>
<link rel="stylesheet" type="text/css" href="/css/<%= web.cssFile %>">
</head>
</body>
</html>
Hoping it will help
What I do in order to avoid having a polluted global scope is to create a script that I can include anywhere.
// my-script.js
const ActionsOverTime = require('#bigteam/node-aot').ActionsOverTime;
const config = require('../../config/config').actionsOverTime;
let aotInstance;
(function () {
if (!aotInstance) {
console.log('Create new aot instance');
aotInstance = ActionsOverTime.createActionOverTimeEmitter(config);
}
})();
exports = aotInstance;
Doing this will only create a new instance once and share that everywhere where the file is included. I am not sure if it is because the variable is cached or of it because of an internal reference mechanism for the application (that might include caching). Any comments on how node resolves this would be great.
Maybe also read this to get the gist on how require works:
http://fredkschott.com/post/2014/06/require-and-the-module-system/

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