Categories: Prototype教程

Prototype – 模板Template

模板用于格式化一组相似的对象并为这些对象生成格式化的输出。

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

这个人很懒,什么都没有留下~

Share
Published by
terry

Recent Posts

在 Chrome 中删除、允许和管理 Cookie

您可以选择删除现有 Cooki…

1 天 ago

自定义指令:聊聊vue中的自定义指令应用法则

今天我们来聊聊vue中的自定义…

1 周 ago

聊聊Vue中@click.stop和@click.prevent

一起来学下聊聊Vue中@cli…

2 周 ago

Nginx 基本操作:启动、停止、重启命令。

我们来学习Nginx基础操作:…

3 周 ago

Vue3:手动清理keep-alive组件缓存的方法

Vue3中手动清理keep-a…

3 周 ago

聊聊React和Vue组件更新的实现及区别

React 和 Vue 都是当…

4 周 ago