当前位置:网站首页>Template engine, making interaction elegant

Template engine, making interaction elegant

2022-06-22 09:19:00 Jdoit CW

The goal is

Understand the template engine
Can use template syntax

Write it at the front

Write it at the front : When we get the data of the server response , How do we render it , Of course, I think you are smart enough to specify a template engine . alas ( I don't want to suffer from Template Strings anymore ), Template engines have a wide range of uses , It can be used for back-end rendering (npm install ), You can also perform front-end rendering ( This article takes the front-end rendering as an example ). Of course, no matter which rendering method , The template syntax is consistent .

1. template engine

This article focuses on the common syntax of template engine , More grammar tips , Please give priority to official documents

file :http://aui.github.io/art-template/zh-cn/

Github: https://github.com/aui/art-template

1.1 Disadvantages of Using Template Strings
  1. Data and HTML String concatenation leads to code confusion , Splicing is error prone , Increase modification difficulty .
  2. Business logic and user interface are mixed , The code is not easy to maintain .
for (var i = 0; i < result.length; i++) {
    
	html += '<!DOCTYPE html>\ <html lang="en">\ <head>\ <meta charset="UTF-8">\ <title>'+ title +'</title>\ </head>\ <body>\ <h1 οnclick="sayHi('+name+')"> Hello ,'+name+'  I this year  '+age+' year </h1>\ <ul>\ <li title="'+hobbies[0]+'">'+hobbies[0]+'</li>\ </ul>\ </body>\ </html>';
}
1.2 The role of template engine
  1. Using the template syntax provided by the template engine, you can Make data and HTML String splicing is more beautiful , Code is easy to maintain .
  2. The template engine enables the data splicing and editing of the user interface JavaScript Business logic separation , Increase program scalability .
  3. Using the template engine, you can Improve development efficiency .
1.3 Use of template engine

Template rendering is a four step process :

  1. Download and import template-web.js file
  2. Write a template where you want to render
  3. Use template Method for data splicing
  4. Render the spliced template string at the specified position

Code demonstration ( The notes are clear )

  <!--  The introduction of the file  -->
    <script src="./template-web.js"></script>
    <div id="box">
        <!--  Use... Where you need to render script Tag write html Templates ( Be careful 1:type="text/html",2:id Required ),type For in script Write in html convenient ,id Easy to determine render target  -->
        <script type="text/html" id="tpl"> <div> <!--  Rendered values must be in "{
     {}}" The parcel  --> <span>{
     {
     name}}</span> <span>{
     {
     age}}</span> </div> </script>
    </div>
    <script> //  When introducing template-web After the document ,template Methods exist  //  Note that one parameter of the method is the template id, The second parameter is the data to be rendered  //  Method returns the concatenated template string  const html = template('tpl', {
      name: ' Chen Wen ', age: 18 }); //  Render the spliced data to the specified location  document.querySelector('#box').innerHTML = html </script>

2. Template syntax

The function of template syntax is to tell the template engine , How to splice data and templates .

2.1 Output

Display the data in the template .

 <h2>{
   {value}}</h2>
 <h2>{
   {a ? b : c}}</h2>
 <h2>{
   {a + b}}</h2>

2.2 Original output

If the data carries HTML label , By default , The template engine will not parse the tag , It will be escaped and output to the original text . If we need to HTML Label effective , You need to add... Before the data @, Parse label .

<h4>{
   {@ value }}</h4>

2.3 conditional

If there is a certain judgment in the rendering of some data ( Render or not ), We can limit it by conditional judgment

 {
   {if  Conditions }} ... {
   {/if}}
 {
   {if v1}} ... {
   {else if v2}} ... {
   {/if}}

Show or not

{
   {if  Conditions }}
	<div> Conditions established   Show me </div>
{
   {else}}
	<div> Conditions not established   Show me </div>
{
   {/if}}

Be careful if Double label

2.4 loop

For the data that the server responds , Most of them are arrays 、json object . There are many such data , In this case, the template syntax loop is used

 {
   {each target}}
     {
   {$index}} {
   {$value}}
 {
   {/each}}

Be careful each Double label , among $index Is the index of the current circular item ,$value Is the value of the current loop item

demo preview :

 Insert picture description here

Code demonstration ( The notes are clear )

 <script src="template-web.js"></script>
    <script type="text/html" id="tpl">
        <ul>
            {
    {
    each data}}
            <li>
                <!--  Be careful $values It's the object , Use ”." To take a value  -->
                <span> full name :{
    {
    $value.name}}</span>
                <span> Age :{
    {
    $value.age}}</span>
            </li>
            {
    {
    /each}}
        </ul>
    </script>
    <script>
        let data = [{
    
            name: ' Jiaxi ',
            age: 27
        }, {
    
            name: ' Zhan Jie ',
            age: 27
        }, {
    
            name: ' Xiaofei ',
            age: 27
        }]
        const html = template('tpl', {
    
            // data: data
            data //es6 The key value data is consistent , Omittable value ,( Note that this must be an object format , Add {})
        });
        document.body.innerHTML = html
    </script>

2.5 Import template variables

When the template processes some native data , May be used JavaScript Methods , But this method template engine does not , At this point, you need to import this method into the template engine ( Import the variables )

<div>$imports.dataFormat(time)</div>
template.defaults.imports. Variable name  =  A variable's value ;
$imports. Variable name 

demo preview :
Original time format

 Insert picture description here

Demand time format
 Insert picture description here

The first way :

 <script src="./template-web.js"></script>
    <script type="text/html" id="tpl">
        <h1>{
    {
    $imports.dateFormat(time)}}</h1>
    </script>
    <script>
        const html = template('tpl', {
    
            time: new Date()
        })
        document.body.innerHTML = html

        //  Define functions that change the format of dates 
        function dateFormat(time) {
    
            return time.getFullYear() + ' year ' + (time.getMonth() + 1) + ' month ' + time.getDate() + ' Japan '
        }
    </script>

Be careful : This method , The function is defined in the global scope , So the template can be used directly $.imports call

The second way

  <script src="./template-web.js"></script>
    <script type="text/html" id="tpl">
        <!--  Methods after exposure , Here you can call , You can also omit $imports -->
        <h1>{
    {
    $imports.dateFormat(time)}}</h1>
    </script>
    <script>
        window.addEventListener('load', function() {
    
            //  Leak out the method , Note that this statement must be written before splicing template data 
            template.defaults.imports.dateFormat = dateFormat;
            const html = template('tpl', {
    
                time: new Date()
            })
            document.body.innerHTML = html

            //  Define functions that change the format of dates 
            function dateFormat(time) {
    
                return time.getFullYear() + ' year ' + (time.getMonth() + 1) + ' month ' + time.getDate() + ' Japan '
            }
        })
    </script>

Be careful : In most cases , Prevent variable pollution , They are generally defined as local methods , use template.defaults.imports. Custom name = Method name Expose the method

At the end

At the end : Template engine has been widely used in the current page rendering , Master its usage , essential . Of course, more usage , We have to rely on the government to greatly : file , I hope we can continue to make breakthroughs , On the way , come on. .

原网站

版权声明
本文为[Jdoit CW]所创,转载请带上原文链接,感谢
https://yzsam.com/2022/173/202206220844302176.html