最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

I am passing an array via ejs with JavaScript. I can get to the values inside ejs but not from JavaScript. Below is more information.

node.js

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

index.ejs

 <script type="text/javascript">

   var FileTypes =  <%=FileTypes%>;
   //Error message on the console - Uncaught SyntaxError: Unexpected token & 

 </script>

Any ideas?

I am passing an array via ejs with JavaScript. I can get to the values inside ejs but not from JavaScript. Below is more information.

node.js

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

index.ejs

 <script type="text/javascript">

   var FileTypes =  <%=FileTypes%>;
   //Error message on the console - Uncaught SyntaxError: Unexpected token & 

 </script>

Any ideas?

Share Improve this question asked Feb 18, 2014 at 15:33 harishvcharishvc 4518 silver badges21 bronze badges 4
  • 1 What is populating <%=FileTypes%>? A templating system? A delimited value like this is not part of standard JavaScript. – Diodeus - James MacFarlane Commented Feb 18, 2014 at 15:39
  • What does the rendered file look like? – Jordan Running Commented Feb 18, 2014 at 15:42
  • @Diodeus OP said in the title, body, and tags: EJS. github./visionmedia/ejs – Jordan Running Commented Feb 18, 2014 at 15:43
  • If that's the case, this injection method is designed to work with HTML, not with injecting code into SCRIPT blocks. – Diodeus - James MacFarlane Commented Feb 18, 2014 at 15:53
Add a ment  | 

1 Answer 1

Reset to default 5

Using the <%= %> tag in EJS will escape the output, so {"application/octet-stream": ... } is being turned into {&quot;application/octet-stream&quot;: ... }, resulting in JavaScript like this:

<script type="text/javascript">                                                                                                                                          
  var FileTypes = {&quot;application/octet-stream&quot;:20,&quot;audio/mpeg&quot;:12,&quot;text/html&quot;:71};
</script>

So, you can see where the "Unexpected token &" is ing from. The solution is to use the <%- %> tag, which won't escape the output:

<script type="text/javascript">
  var FileTypes = <%- FileTypes %>;
  //      here -----^
</script>

...and will give you what you want:

<script type="text/javascript">                                                                                                                                          
  var FileTypes = {"application/octet-stream":20,"audio/mpeg":12,"text/html":71};
</script>             
发布评论

评论列表(0)

  1. 暂无评论