Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Pass script src into Pug template

I'm trying to get my Pug template to render a script using Express. My file structure is as follows:

views
    public
        index.jade
        main.js

index.js

I have tried passing the name of the script as an argument to res.render('public/index', { bundle: '/main.js' }) with no luck.

Contents of my index.js:

const app = express();

app.set('view engine', 'jade');

app.use(express.static(path.join(__dirname, 'views/public')));

app.use('*', (req, res, next) => {
    res.render('public/index', { bundle: '/main.js' });
});

Contents of my index.jade:

doctype html
html
    head
        title SSR React
    body
        div#root
        script(src='#{bundle}')

I'm getting a strange error in the console. The name of the script is coming through, but I'm getting the error

Uncaught SyntaxError: Unexpected token <

The contents of main.js when I look at the console are as follows:

<!DOCTYPE html><html><head><title>SSR React</title></head><body><div id="root"></div><script src="/main.js"></script></body></html>

so, just the minified HTML which is being transpiled from Pug.

Can anyone shed some light here? Am I configuring Express incorrectly? Thanks.

like image 506
brownac Avatar asked Nov 15 '25 16:11

brownac


1 Answers

While writing inline JavaScript in Jade template you need to add a dot after the script tag. Also you should indent your code.

For example include external js like:

script(type='text/javascript', src='/socket.io/socket.io.js')

Inline js like:

script(type='text/javascript').
like image 185
Shivani Sonagara Avatar answered Nov 18 '25 07:11

Shivani Sonagara



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!