简体   繁体   中英

Pug string interpolation for linked JavaScript files

What I'm Trying To Do

I have a NodeJS webserver that serves an HTML and JavaScript file using Express and Pug . It looks something like this:

index.pug

html
    head
        title Hello
    body
        h1 Hello World!
        script(src='script.js')

app.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);

script.js

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 (ie {age: 91, name: 'George P. Burdell'} ).

The Problem

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:

index.pug

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.

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:

index.pug

html
    head
        title Hello
    body
        h1 Hello World!
        script.
            var age = #{age};
            var name = #{name};
        script(src='script.js')

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!

EDIT

app.js

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM