template content template element

foreword

The HTML content template element contains only global attributes and is a mechanism for holding client-side content that is not rendered when the page is loaded but can then be instantiated at runtime using JavaScript.

Think of a template as a piece of content that is stored in the document for later use. While the parser does process the content of the <template> element when the page is loaded, it does so only to ensure that the content is valid; however, the content of the element is not rendered.

For example, you need ajax to refresh a list. The previous method is to generate HTML backend, or add it after the front end is built with DOM. But now with the template tag, the HTML structure does not need program management. You only need to add ajax at a specific location Just the requested data, such as the src of img or other text, and then clone the DOM and add it to the list.

Template element example

The following code verifies that the element and content will not be rendered (displayed) when the <template> element loads the page.

<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Document</title>
    <!-- reset.css -->
    <!-- <link rel="stylesheet" href="reset.css"> -->
</head>
<body>
<!-- 内容模板 -->
	<template>
  		<p>文字文字文字</p>
	</template>
<!-- end -->
</body>
</html>

insert image description here
After running, the page does not have any elements and content. F12 checks the elements and finds the phenomenon as shown in the figure.

Called a document fragment , let's expand it.
insert image description here
That's right, this requires JS to manipulate the content of the document fragment to display it. The specific explanation and example have been shown in the preface.

Vue renders template elements

Render a list of lists in a template element via the v-for directive

HTML:
<div id="app">
  <template>
    <ul>
      <li v-for="list in list">{
    
    {
    
     list }}</li>
    </ul>
  </template>
</div>

vue:
var vm = new Vue({
    
    
  el:'#app',
  data:{
    
    
    list:["张三","李四","王五"]
  },
})

insert image description hereinsert image description here
As shown in the figure, the <template> element has been automatically removed, leaving only the structure and data we want to render.

In fact, many people should have done similar things before, hide a piece of html, then clone it and modify the properties or content inside, get a DOM, add it to the list and display it, and use it to refresh the ajax list.

Guess you like

Origin blog.csdn.net/m0_68669764/article/details/128370561