简体   繁体   English

如何将变量传递到javascript模板中?

[英]How to pass variable into javascript template?

I trying to learn js templates and wrote following page: 我试图学习js模板并编写了以下页面:

<!DOCTYPE html>
 <html>
 <head>
   <meta charset="utf-8">
   <script src="http://code.jquery.com/jquery-latest.js"></script>
   <script src="http://cdnjs.cloudflare.com/ajax/libs/lodash.js/0.9.0/lodash.js"></script>

 </head>
 <body>

 <div id="helloDiv">init text</div>


<script type="text/template" id="test">
<% hello world %>!
</script>
<script>


$('#helloDiv').html( 
  _.template( $('#test').html().trim(),world : 'EARTH') 
);

</script>


</body>
</html>

Expected behaviour: I want to see hello EARTH! 预期的行为:我想向hello EARTH!

But I see init text 但是我看到init text

What do I wrong? 我怎么了

There is a lot wrong here. 这里有很多错误。 You should learn to look at your JavaScript console and do some debugging before posting questions, because there is so much wrong that it's difficult to tell what thing is causing your specific error. 在发布问题之前,您应该学会查看JavaScript控制台并进行一些调试,因为存在太多错误,很难分辨是什么原因导致了您的特定错误。

  1. There is no such thing as a "JavaScript template". 没有“ JavaScript模板”之类的东西。 That's an Underscore template (or, lodash in this case), which is a library and not at all something built into JavaScript. 这是一个下划线模板(或在这种情况下,lodash),这是一个图书馆,而不是在所有内置到JavaScript的东西。

  2. You're using <% %> wrong. 您使用的是<% %>错误。 If you want to interpolate the value of "EARTH" for the "world" variable, you need something along the lines of 如果要为“ world”变量内插“ EARTH”的值,则需要以下内容:

     hello <%= world %>! 

    As it is, with <% hello world %> , you're telling the template to invoke a function called hello with a variable called world . 实际上,使用<% hello world %> ,您要告诉模板调用一个名为hello的函数以及一个名为world的变量。 Even if #3 below were fixed, you'd still be getting an error. 即使下面的#3已修复,您仍然会遇到错误。

  3. Finally, and most importantly, you have a very obvious syntax error. 最后,最重要的是,您有一个非常明显的语法错误。 You're missing {} around your world: 'EARTH' . 您在world: 'EARTH'缺少{} world: 'EARTH' Your script block won't even parse, and there should be a very obvious error on the JavaScript console telling you the exact line on which this syntax error occurs. 您的脚本块甚至都不会解析,并且JavaScript控制台上应该有一个非常明显的错误,告诉您此语法错误发生的确切行。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM