JADE + EXPRESS: Iterating over object in inline JS code (client-side)?

与世无争的帅哥 提交于 2019-11-27 21:33:18

The entire script tag (everything indented under it) is going to be passed through raw without further parsing. Jade does HTML templating not HTML templating plus nested javascript templating. To pass your pins variable from jade local template variable data to script source code, you'll have to do some other approach like using raw jade to render a tiny script tag that just calls your initialize function with the pins data as a literal, or stick your pins data into the dom somewhere and then read it from there. Something along these lines below your script tag (pseudocode, haven't tested)

- if (typeof(pins) != null)
  != "<script type='text/javascript'>"
  != "var pins = [];"
  - forEach pin in pins
    != "pins.push(new Pin(" + pin.latitude + ", " + pin.longitude + "));"
  != "initialize(pins);"
  != "</script>"

I passed the value as a hidden input element, e.g.:

    input(type='hidden', id='variableName', value='#{variableName}')

Accessed via jQuery:

    $("#variableName").val()

Joe

You can use this:

script
  console.log(#{var_name});

the script tags are purely text, you can't easily mix the Jade to generate this javascript, it's usually a reflection of poor design. You can just serialize things as JSON that you need on the client or use express-expose to do this

server side

JSON.stringify(users)

client side

var users=JSON.parse(("#{users}").replace(/&quot;/g,'"'));
Erjim

I had a similar issue and this line of code solved it:

var myvar  = !{JSON.stringify(mydata)};

The answer came originally from this post

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!