模板用于格式化一组相似的对象并为这些对象生成格式化的输出。
Prototype 提供了一个Template类,它有两个方法 –
- Template() – 这是一个构造函数方法,用于创建模板对象并调用evaluate()方法来应用模板。
- evaluate() – 此方法用于应用模板来格式化对象。
创建格式化输出涉及三个步骤。
- 创建模板– 这涉及创建预格式化的文本。此文本包含带格式的内容以及#{fieldName}值。当使用实际值调用evaluate()方法时,这些#{fieldName}值将被实际值替换。
- Defining actual values – 这涉及以键和值的形式创建实际值。这些 Key 会映射到模板中,并会被相应的值替换。
- Mapping Keys and replacing Values – 这是调用evaluate()的最后一步,格式化对象中所有可用的键都将被定义的值替换。
例子一
第1步
创建模板。
var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');第2步
准备我们的一组值,这些值将在上面的对象中传递以获得格式化输出。
var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];步骤 3
最后一步是填写模板中的所有值并产生最终结果如下 :
records.each( function(conv) {
alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});所以,让我们把所有这三个步骤放在一起:
<html>
<head>
<title>Prototype examples</title>
<script type = "text/javascript" src = "https://cdn.bootcdn.net/ajax/libs/prototype/1.7.3/prototype.min.js"></script>
<script>
function showResult() {
// Create template with formatted content and placeholders.
var myTemplate = new Template('The \ TV show #{title} was directed by #{author}.');
// Create hashes with the required values for placeholders
var record1 = {title: 'Metrix', author:'Arun Pandey'};
var record2 = {title: 'Junoon', author:'Manusha'};
var record3 = {title: 'Red Moon', author:'Paul, John'};
var record4 = {title: 'Henai', author:'Robert'};
var records = [record1, record2, record3, record4 ];
// Now apply template to produce desired formatted output
records.each( function(conv) {
alert( "Formatted Output : " + myTemplate.evaluate(conv) );
});
}
</script>
</head>
<body>
<p>Click the button to see the result.</p>
<br />
<br />
<input type = "button" value = "Result" onclick = "showResult();"/>
</body>
</html>作者:terry,如若转载,请注明出处:https://www.web176.com/prototype/8251.html
支付宝
微信