Search code examples
expresspug

How to render string into javascript in pug


So i am using Express and create an MVC application. I have a list of email that i want to put into javascript variable in the front end and create an auto complete so currently the controller looks like this:

controller.js

res.render('/page',{emails: emails})

the emails is a JSON structured, can be stringified if needed. and my pug template is as follow

div
    input (type = "text" id="suggestion")
    div (class = "custom-suggestion" id="suggestion-list")

and at the end, i override custom scripts block with:

script.
  var emailList = ///////////i want the email from controller's data

How can i achieve this? Any suggestion as long as i can pass the data to the javascript side will be considerable

EDIT To make the code clearer:

app.js

var app = express();
app.set('view engine', 'pug');
router = express.Router();
router.get('/',function(req,res,next){
    emails = ['abcd@abc.com','def@def.com','123@123.com'];
    res.render('index', {emails:emails})
})
app.use(router);

index.pug

extend layout

block content
    h1= title

block scripts
    script
       emails= emails /// not working

       ////////////// how to render this line as 
       ////////////// emails = ['abcd@abc.com','def@def.com','123@123.com'] 

Solution

  • You can use interpolation to do this:

    script.
      emails= !{JSON.stringify(emails)};
    

    Note that there's a period after the script tag, this tells pug to treat the content inside the tag to be plain text. Without that period it will create a script tag then an email tag (<script><email></email></script>) which is not what you want here.

    Now that you're in plain text mode you can output the template variable into a JavaScript variable using an unescaped interpolation command (!{...}) with a stringify inside.