Reputation: 41
I have a NodeJS webserver that serves an HTML and JavaScript file using Express and Pug. It looks something like this:
html
head
title Hello
body
h1 Hello World!
script(src='script.js')
const express = require('express');
var app = express();
app.set('view engine', 'pug');
app.get("/", (req, res) => {
res.render("index", {
age: 91,
name: 'George P. Burdell'
});
});
app.listen(8080);
var person = {
age: #{age},
name: #{name}
};
(Taken from and added on to GitHub example)
I want to be able to swap the #{age}
and #{name}
placeholders with the values indicated in the res.render()
function (i.e. {age: 91, name: 'George P. Burdell'}
).
As of right now, the values are not swapped and the console spits out an error indicating the lines with placeholders #{age}
and #{name}
are not recognized. The placeholder values are swapped only if the JavaScript code in script.js are brought into the .pug file as an internal script like so:
html
head
title Hello
body
h1 Hello World!
script.
var person = {
age: #{age},
name: #{name}
};
But what I want to be able to do is swap the values directly from an external script file such as in the initial setup. I've had no luck finding an easy way to do this apart from having the code "live" inside the .pug file.
Upvotes: 1
Views: 929
Reputation: 41
So I have a workaround. What you can do is set global variables in an internal script tag in the .pug file which can then be interpolated using pug. As a visual, here's what I mean:
html
head
title Hello
body
h1 Hello World!
script.
var age = #{age};
var name = #{name};
script(src='script.js')
var person = {
age: age, // the age variable from the internal script is used
name: name // the name variable from the internal script is used
};
app.js remains the same!
res.render("index", {
age: 91,
name: 'George P. Burdell'
});
should be
res.render("index", {
age: "91",
name: "'George P. Burdell'"
});
to keep the data type after swapping!
Please let me know if there is an even better way to solve this! For now, this is the accepted answer.
Upvotes: 1