2011-04-15 148 views
24

例如,查看源代码在Joel Spolsky's public career profileHTML标签如何在脚本标签内工作?

<script type="text/html" id="stackexchangeanswerswidget"> 
    <h3>Top Answers</h3> 

    <div class="answers"> 
    </div> 

</script> 

<script type="text/html" id="topanswer"> 
    <div class="top-answer"> 
     <div class="top-answer-stats">{{= shared.htmlEncode(Score) }}</div> 
     <span class="top-answer-title"><a href="{{=AnswerLink}}">{{= shared.htmlEncode(Title) }}</a></span> 
     <a class="add-answer">add</a> 
     <br class="clear" /> 
    </div> 
</script> 

<script type="text/html" id="answer-view"> 
    <div class="answer"> 
     <div class="answer-stats {{= shared.htmlEncode(Site.toLowerCase().replace(/ /g, '')) }}"> 
      <div class="score"> 
       <strong>{{= shared.htmlEncode(Score) }}</strong> 
       <div class="votecount">votes</div> 
      </div> 
      <img class="answer-logo" src="{{= shared.htmlEncode(FaviconUrl) }}" /> 
     </div> 
     <div class="answer-content"> 
      <span class="q">Q:</span> 

      <div class="answer-top"> 

       <a class="answer-title" href="{{= shared.htmlEncode(AnswerLink) }}">{{= shared.htmlEncode(Title) }}</a><br /> 
      </div> 

      <span class="a">A:</span><div class="answer-body">{{= Body }}</div> 

      <div class="more-button" style="text-align:center; clear:both; display:none;"><a class="more">More</a></div> 

     </div> 
    </div> 
</script> 

如何HTML标签脚本标签中工作?和/或什么样的技术用于这些html标签,以及模板内码{{= .... }}里面的脚本标签?

+0

可能是像小胡子 - http://mustache.github.com/ – Kai 2011-04-15 15:50:40

回答

24

你可以把你的<script>标签想要的任何东西。如果您指定的内容类型不是Javascript(或者浏览器可以理解的另一种脚本语言),则它不会被浏览器解释,您只能以纯文本的形式访问它。由于<script>标签的内容被视为CDATA,所以内容不会被解析,您可以在内容中存储未加引号的XML或HTML(只要您不会在内容中放置</script>标签,因为这会关闭您的元素)。

例如,在SVG Web中使用了一个polyfill,它允许您在HTML中使用内联SVG,并在支持它的浏览器中将其转换为本机SVG,或者在不支持的浏览器中将Flash转换为本机SVG。它允许将SVG嵌入到不支持本机的浏览器中,方法是将其封装在<script>标记中,这样浏览器就不会尝试并将其解析为HTML。

在SO carreers的情况下,它看起来像他们存储使用模板和Backbone.jsUnderscore.js<script>标签,因为这是一个方便的地方贴模板HTML。这里就是他们抓住模板,并将其提供给下划线的模板引擎的代码片段:

TopAnswerView = Backbone.View.extend({ 
     template: _.template($("#topanswer").html()), 
     events: { 
      "click .add-answer": "addAnswerToCV" 
     }, 
7

关键在于脚本的类型属性。通过将其设置为type =“text/html”它不会被浏览器的JavaScript引擎运行。相反,它用于其他的东西,比如模板。这个例子似乎是在模板中使用这些标签。

看看这个MIX 2011网络直播,演示如何类似的东西在Knockout.js使用:

http://channel9.msdn.com/events/mix/mix11/FRM08

+0

这里有一些例子:HTTP ://blog.reybango.com/2010/07/09/not-using-jquery-javascript-templates-youre-really-missing-out/, – Shawn 2011-04-15 16:08:44