1

Following is a pug snippet. I need to dynamically populate the user in chatConfig object.

 script.
  var chatConfig = {
    user : 'foo',
    pass : 'bar',
  }

From my express , I am rendering as

  resp.render('user/index', {username:req.user});

How do I pass the value of req.user to user key inside script.?

Koko
  • 131
  • 1
  • 10

2 Answers2

2

Brmmmm is on the right track, but you need to get your JavaScript to use the variable as an object, not as a variable. You can stringify the variable to get it to work as a JavaScript object.

doctype html
html(lang='en')
  head
    title Jade
    - var test = {prop1: "Hi there", prop2: "Another test"};
    script(type='text/javascript').
      var test2 = !{JSON.stringify(test)};
      console.log(test2, test2.prop1, typeof test2);
  body
    h1 Jade - template engine
    #container.col
      p I'm some Jade

Live Example; check the browser console/Codepen console to see what the console.log statements output.

Shea Hunter Belsky
  • 2,815
  • 3
  • 22
  • 31
  • 1
    Sorry I didn't realise it was an object. The variable name "username" mislead me lol . Sorry my mistake. – Brmmmm Mar 23 '17 at 10:02
1

I think it should look like this:

script.
  var chatConfig = {
    user : '${username}',
    pass : 'bar',
  }
Brmmmm
  • 152
  • 7