template-parser

模版的几种表示方式

  1. 模版元素,HTML5 中的新玩意儿,template :
<template id="template">
     <p>This is a template</p>
</template>

在支持 template 标签的浏览器中是看不到任何信息的,不支持此标签的会显示: This is a template

  1. 在 template 标签诞生之前一般都是利用 script 标签来实现模版功能的:
<script type="text/template" id="template">
    <p>This is the second type template</p>
</script>

这是利用了 script 标签中的内容天生不显示的特性来达到目的的,另外,text/template 这个 type 是不存在的,只是为了凸显其作用,而另行与标准之外的设定。

  1. 模版,模版,见名知意,网页中的模版,就是不需要显示出来,只要为需要显示的页面部分做出规范。
    可以看出主要就是不需要其显示,而又能取出需要的内容:
<div style="display:none" id="template">
    <p>This is the third type template</p>
</div>

innerHTML、outerHTML

简述其区别就是:

innerHTML:从对象起始位置到终止位置的全部内容,不包括 html 标签。
outerHTML:除了包含 innerHTML 的全部内容外,还包含 html 标签本身。

<div id="div">This is a div</div>
// 'This is a div'
console.log(div.innerHTML);
// '<div id="div">This is a div</div>'
console.log(div.outerHTML);

取出模版元素

// template tag
template.content
// script
template.innerHTML
// hidden tag
template.outerHTML

template-parser

当然,解析模版是少不了 fragment 的帮忙的。

var toFragment = require('./fragment');

/**
 * 将模版解析为文档碎片
 * 可以传入如下几种模式的参数:
 * id 选择器: '#some-template-id'
 * 模版字符串: '<div><span>my template</span></div>'
 * DocumentFragment 对象
 * 模版节点
 */
module.exports = function(template) {
  var templateNode;
  
  // 如果是 DocumentFragment 对象,直接返回
  if(template instanceof window.DocumentFragment) {
    return template;
  }

  if(typeof template === 'string') {
    // '#' 开头的字符串当作 id 选择器处理
    if(template.charAt(0) === '#') {
      templateNode = document.getElementById(template.slice(1));
      if(!templateNode) return;
    // 不是 '#' 开头的,作为模版字符串,直接处理
    } else {
      return toFragment(template);
    }
  // 模版节点,后续继续处理
  } else if(template.nodeType) {
    templateNode = template;
  } else {
    return;
  }
  
  // 浏览器支持 template 标签,其 content 已经是一个文档碎片
  if(templateNode.tagName === 'TEMPLATE' && templateNode.content) {
    return templateNode.content;
  }
  // script 标签中的内容会被当作字符串处理
  if(templateNode.tagName === 'SCRIPT') {
    return toFragment(templateNode.innerHTML);
  }
  // 普通节点,连同其标签本身一起作为字符串去处理
  return toFragment(templateNode.outerHTML);
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容

  • 这篇笔记主要包含 Vue 2 不同于 Vue 1 或者特有的内容,还有我对于 Vue 1.0 印象不深的内容。关于...
    云之外阅读 5,096评论 0 29
  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 135,286评论 19 139
  • HTML标签解释大全 一、HTML标记 标签:!DOCTYPE 说明:指定了 HTML 文档遵循的文档类型定义(D...
    米塔塔阅读 3,410评论 1 41
  • 下载安装搭建环境 可以选npm安装,或者简单下载一个开发版的vue.js文件 浏览器打开加载有vue的文档时,控制...
    冥冥2017阅读 6,123评论 0 42
  • 产品功能:创业公司产品介绍。 所解决的问题:为关注互联网行业创新的人们提供一个简单和专注的获得信息的方式。 产品差...
    性感瓶底儿阅读 1,257评论 1 3