简体   繁体   中英

Unable to pass data from jade to javascript

I am learning jade and following is my code snippet

extends layout


block content
  h1= title
  p Token is #{token.access_token}
      script(type='text/javascript')
          var tokenValue = JSON.parse(token);
          sayhi(tokenValue);

Inside my test.js I have

function sayhi(token) {
    console.log(token);
}

If I send a text from sayhi - it works perfectly but if i send tokenValue - I get following error:

unexpected text ;

   at Object.Lexer.fail (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/lexer.js:872:11)
   at Object.Lexer.next (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/lexer.js:931:15)
   at Object.Lexer.lookahead (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/lexer.js:113:46)
   at Parser.lookahead (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:102:23)
   at Parser.peek (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:79:17)
   at Parser.tag (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:751:22)
   at Parser.parseTag (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:737:17)
   at Parser.parseExpr (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:211:21)
   at Parser.block (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:707:25)
   at Parser.tag (/home/shardul/WebstormProjects/trial/node_modules/jade/lib/parser.js:816:24)

A few issues that i see here.

  1. You need to define the script as a text block, using a period.
  2. token is currently a variable in Jade that needs to be encoded for JS, not decoded.
  3. You'll need to interlope token to the text block.

Final code:

block content
  h1= title
  p Token is #{token.access_token}
      script(type='text/javascript').
          var tokenValue = #{JSON.stringify(token)};
          sayhi(tokenValue);

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