JS Template Implementation Method _javascript skills

Source: Internet
Author: User

Overview

When we use JS to render the DOM, we typically use a string to create the DOM and then append it to the parent element, and if the additional DOM is dynamic and variable, you need to write a lot of logic in the function. This poses a more serious problem if the control is implemented.

A common solution to this problem is to use a template, which is used as a configuration item to pass in the control, separating the data from the rendering. The specific implementation methods are as follows:

    1. String substitution, using a regular match to replace the data into a string.
    2. Render function, the function returns a string.
    3. Template engine, you can perform functions in a string (built-in or custom)

Replace (substitute)

String replacement is the simplest way to implement a template, look at the specific implementation:

1. Define the substitution function

Copy Code code as follows:

/**

* Replace the field in the string.

* @param {string} str template string

* @param {Object} o JSON data

* @param {REGEXP} [REGEXP] matches a regular expression of a string

*/

function Substitute (str,o,regexp) {

Return str.replace (RegExp | |/\\?\{([^{}]+) \}/g, function (match, name) {

Return (o[name] = = undefined)? ': O[name];

});

}

2. Use Configuration items:

Copy Code code as follows:

var config = {

Data: {value: ' 123 ', text: ' ABC '},

Template: ' <label>{text}</label><input type= ' text ' value= ' {value} '/> '

};

3. In the process of creating the DOM we call this:

Copy Code code as follows:

var str = substitute (template,data);

$ (str). Appendto (' body ');

By using the examples above, we have completed the decoupling of data and strings, which can be used flexibly in the control, and most of the JS frameworks now provide templates for this type.

On this basis can have the following extensions, interested can be achieved by themselves:

1. Use numbers instead of parameter names:

such as ' <label>{0}</label><input type= ' text ' value= ' {1} '/> '

2. Nesting using Object properties:

such as ' <label>{obj.name}</label><input type= ' text ' value= ' {obj.value} '/> '

Advantages: Simple to implement and easy to understand.

Disadvantages: Only a simple data structure, unable to process loops, conditional statements.

Rendering Method (Render)

We can handle very complex logic in the render function, and we can pass the render function as a parameter to the configuration item.

Configuration items:

Copy Code code as follows:

var config = {

Data: [{value: ' 0 ', text: ' abc '},{value: ' 1 ', Text: ' BCD '}],

Renderer:function (obj) {

if (obj.value = = ' 0 ') {

return obj.text;

}else{

Return '

}

}

};

When in use:

Copy Code code as follows:

for (var i = 0; i< data.length; i++) {

var obj = Data[i],

str = config.renderer (obj);

$ (str). Appendto (' body ');

}

This is a good solution when dealing with loops, conditional statements.

Advantages: The realization is relatively simple, the realization is flexible, can satisfy the complex data structure, easy to debug

Disadvantages:

    1. Rendering functions are not easy to understand as configuration items.
    2. When the function is longer, the configuration item is bloated.
    3. Each scene needs to implement its own rendering function.

Template Engine (xtemplate)

Each JS UI library will have a powerful template engine, and a template engine needs to implement the following features:

1. String replacement

2. Dealing with complex statement conditions, loops

3. Using inline functions

4. Allow users to pass in custom functions

There are 2 common ways to implement the current template engine:

1. Use the regular parse string to execute the special statement logic in it, replacing the corresponding data

Let's take a look at an example of the Kissy template:

' Hello, {{{#each users}}{{#if _ks_value.show}}{{_ks_value.name}}{{/if}}{{/each}}}. '

Above this is a template that can handle loops, conditional statements.

2. Parse the string, generate a syntax tree, and perform a replacement for the corresponding label or data.

The following is the use of ext xtemplate:

Copy Code code as follows:

var TPL = new Ext.xtemplate (
' <p>{name}\ ' s favorite beverages:</p> ',
' <tpl for= ' drinks ' > ',
' <div>-{.} </div> ',
' </tpl> '
);
Tpl.overwrite (panel.body, data);

Advantages: Powerful and flexible

Disadvantage: The use of complex, more difficult to understand. Not easy to debug.

Problem thinking

1. Templates are used in controls to separate data from the DOM, but if a control contains a large number of templates, it increases the user's workload and is not easy to debug and needs to be weighed against.

2. If a large number of controls use the same template, and the same data structure, each control is individually configured for ease of use, a better scenario is to allow the parent control to configure the template.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.