1

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 = ['[email protected]','[email protected]','[email protected]'];
    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 = ['[email protected]','[email protected]','[email protected]'] 
3
  • Try to add what have you tried and what does not work. Add errors, if any. Doesn't emailList =emails; work? Commented Sep 25, 2018 at 7:49
  • no, emailList =emails doesnt work, this one is classified project so i can't really share too much, but lemme give a bit additional details in a moment Commented Sep 25, 2018 at 7:53
  • Check this answer stackoverflow.com/a/20294680. Does it work? Commented Sep 25, 2018 at 12:21

1 Answer 1

2

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.