node.js - Howto pass array values via from ejs to Javascript? -


I am passing an array via Java via EJS. I can get value inside ejs, but not javascript Below is more information.

node.js

  file type = {"application / octet-stream": 20, "audio / mpeg": 12, "text / html": 71} Res.render ('index.ejs', {FileTypes: JSON.stringify (file type)});  

index.ejs

  & lt; Script type = "text / javascript" & gt; Var file type = & lt;% = file type% & gt;; // Error message on console - Unwanted syntax error: Unexpected token & amp; & Lt; / Script & gt;  

Any ideas?

& lt; % =%> In EJS Tag output will be saved, so {"application / octet-stream": ...} is being converted to {& amp; Quot; Application / octet-stream & amp; Quot;: ...} , resulting in JavaScript in this way:

  & lt; Script type = "text / javascript" & gt; Var file type = {& amp; Quot; App / octet-stream & amp; Quot; 20, & quot; Audio / mpeg & amp; Quot; 12, & quot; Text / html & amp; Quot ;: 71}; & Lt; / Script & gt;  

So, you can see that "unexpected token & amp;" The solution is coming from & lt;% -% & gt; tag, which will not escape the output:

  & lt; Script type = "text / javascript" & gt; Var file type = & lt;% - file type% & gt;; // here ----- ^ & lt; / Script & gt;  

... and will give you whatever you want:

  & lt; Script type = "text / javascript" & gt; Var File Type = {"Application / Octet-Stream": 20, "Audio / MPEG": 12, "Text / html": 71}; & Lt; / Script & gt;  

Comments