简体   繁体   English

如何使用文字DOM标记作为原型模板?

[英]How can I use literal DOM markup as a Prototype Template?

Prototype's Template class allows you to easily substitute values into a string template. 原型的Template类使您可以轻松地将值替换为字符串模板。 Instead of declaring the Template source-string in my code, I want to extract the source-string from the DOM. 我不想在我的代码中声明Template源字符串,而是要从DOM中提取源字符串。

For example, in my markup I have an element: 例如,在我的标记中,我有一个元素:

<div id="template1">
  <img src="#{src}" title="#{title}" />
</div>

I want to create the template with the inner contents of the div element, so I've tried something like this: 我想使用div元素的内部内容创建模板,因此我尝试了以下操作:

var template = new Template($('template1').innerHTML);

The issue is that Internet Explorer's representation of the innerHTML omits the quotes around the attribute value when the value has no spaces. 问题是,当值没有空格时,Internet Explorer的innerHTML表示将省略属性值周围的引号。 I've also attempted to use Element#inspect , but in Internet Explorer I get back a non-recursive representation of the element / sub-tree. 我也尝试使用Element#inspect ,但是在Internet Explorer中,我得到了元素/子树的非递归表示。

Is there another way to get a Template-friendly representation of the sub-tree's contents? 还有另一种方法来获取子树内容的模板友好表示吗?

Looks like you can embed the template source inside a textarea tag instead of a div and retrieve it using Element#value . 看起来您可以将模板源嵌入到textarea标签(而不是div ,然后使用Element#value检索它。

Certainly makes the markup a little weird, but it still seems reasonably-friendly to designers. 当然会使标记有些怪异,但对设计师来说仍然似乎相当友好。

Additionally, as Jason pointed out in a comment to the original question, including the img tag in the textarea prevents a spurious request for an invalid image. 此外,正如杰森(Jason)在对原始问题的评论中所指出的那样,在文本区域中包含img标签可防止虚假请求无效图像。

Resig to the rescue: 进行救援:

You can also inline script: 您还可以内联脚本:

 <script type="text/html" id="user_tmpl"> <% for ( var i = 0; i < users.length; i++ ) { %> <li><a href="<%=users[i].url%>"><%=users[i].name%></a></li> <% } %> </script> 

Quick tip: Embedding scripts in your page that have a unknown content-type (such is the case here - the browser doesn't know how to execute a text/html script) are simply ignored by the browser - and by search engines and screenreaders. 快速提示:在页面中嵌入具有未知内容类型的脚本(在这种情况下-浏览器不知道如何执行文本/ html脚本)将被浏览器以及搜索引擎和屏幕阅读器忽略。 It's a perfect cloaking device for sneaking templates into your page. 这是用于将模板潜入页面的理想掩盖设备。 I like to use this technique for quick-and-dirty cases where I just need a little template or two on the page and want something light and fast. 我喜欢将这种技术用于快速处理的情况,在这些情况下,我只需要在页面上放置一个或两个小模板,而又希望它们又轻又快。

and you would use it from script like so: 您可以从脚本中使用它,如下所示:

 var results = document.getElementById("results"); results.innerHTML = tmpl("item_tmpl", dataObject); 

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

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