Starting from scratch: learning the front-end template engine with Art-template

Introduction to Art-template

Art-template is a fast, simple and feature-rich template engine based on JavaScript.

Features and advantages of Art-template

  1. Fast and efficient: Art-template adopts the mechanism of static compilation and incremental rendering, which makes it have excellent performance and low memory consumption when rendering large-scale data.
  2. Easy to use: Art-template uses an intuitive and concise syntax, easy to use and suitable for learning front-end template engines from scratch.
  3. Conditional judgment and loop: Art-template provides a wealth of conditional judgment and loop statements, making it easy to handle complex business logic and data display requirements in the template.
  4. Dynamic data processing: Art-template supports the use of filters (filters), which can format, convert and process data to meet different needs.
  5. Organization and management of template files: Art-template supports the organization and modularization of template files, which can better manage and reuse template codes and improve development efficiency.
  6. Comprehensive documentation and community support: Art-template provides detailed official documentation and examples, as well as active community discussions and contributions, making it easy for users to get help and solve problems.

Comparison with other template engines

  1. Performance advantage: Compared with some other common template engines, Art-template has excellent performance, especially when dealing with large-scale data and complex rendering tasks.
  2. Concise and easy to use: The grammar design of Art-template is simple and clear, easy to learn and use, especially suitable for novice developers to get started.
  3. Dependency: Art-template does not depend on other JavaScript libraries or frameworks, and can be used independently or integrated with various front-end frameworks (such as Vue, React).
  4. Rich functions: Art-template provides a wealth of functions and features, including conditional judgment, loops, filters, etc., to meet the needs of various data display and business logic.

Install and configure Art-template

Install using npm

  1. Open the command line terminal and enter the directory where your project is located.
  2. Run the following command to install Art-template in your project:
    npm install art-template
    
  3. After the installation is complete, you can import the Art-template module in the code of the project using a method similar to requireor , for example:import
    const template = require('art-template');
    

Direct import via CDN

  1. <script>Add the Art-template's CDN link in the tag in the HTML file . In this way, the browser will automatically download and load the Art-template.
    <script src="https://cdn.jsdelivr.net/npm/[email protected]/dist/template-web.js"></script>
    
  2. Once Art-template is introduced, you can use global variables in JavaScript code templateto access Art-template's functionality.

Configure and initialize Art-template in the project

  1. If installed using npm, configuration and initialization can be done in JavaScript code. Through template.defaultsthe object, you can set the global configuration options of Art-template, such as the start and end characters of the template tag, whether to cache the compiled template, etc. The sample code is as follows:

    template.defaults.delimiters = ['{
          
          {', '}}']; // 设置模板标签的起止字符
    template.defaults.cache = false; // 禁用模板缓存
    
  2. If Art-template is imported via CDN, no additional configuration and initialization steps are required. templateJust use global variables directly in your JavaScript code .

Template Syntax and Basic Usage

1. Interpolation expressions

Use double braces { { }}to insert dynamic data in the template. For example:<p>{ {name}}</p>

2. Judgment and loop

Use { { if }}and { { each }labels to implement conditional judgment and loop statements. For example:

{
    
    {
    
    if score >= 60 }}
    <p>及格</p>
{
    
    {
    
    else}}
    <p>不及格</p>
{
    
    {
    
    /if}}

{
    
    {
    
    each list as item}}
    <li>{
    
    {
    
    item}}</li>
{
    
    {
    
    /each}}

3. Filter

Use the pipe character |followed by the filter name to process and format the data. For example:{ {time | formatTime}}

4. Comments and special output

Use { {! }}to comment out content in templates, and to {%= %}output content containing HTML characters without escaping.

Write template files

1. Definition and organization of template files

Define templates in HTML files using <script>tags, or store templates in external files and <script>import them via tags.

<script id="template1" type="text/html">
    <h1>{
      
      {
      
      title}}</h1>
</script>

<script src="template.js"></script>

2. Use of nested templates and partial templates

Introduce other templates as sub-templates through variables in a template, and have their own independent data.

<script id="template2" type="text/html">
    <h2>{
      
      {
      
      subTitle}}</h2>
    {
      
      {
      
      include 'template1'}}
</script>

3. Bring in external data and dynamically generate content

By passing in the data object, the properties of the data object are used in the template to dynamically generate content.

const data = {
    
    
    title: 'Hello Art-template',
    subTitle: 'This is a sub title'
};
const html = template('template2', data);

Rendering and Data Processing

1. Create a rendering function and pass in data

Use template.compilethe method to create a render function, and pass in the data by calling the function to render the template.

const render = template.compile('<h1>{
    
    {title}}</h1>');
const data = {
    
    
    title: 'Hello Art-template'
};
const html = render(data);

2. Acquisition and output of rendering results

Save the rendered result into a variable and output it to the page.

const html = template('template1', {
    
    title: 'Hello Art-template'});
document.getElementById('container').innerHTML = html;

3. Precautions

When complex processing of data is required, it can be achieved by defining filters . A filter is a function that takes input data and returns the processed result.

Tips and Ways to Improve Efficiency

1. Template reuse and modularization

  • 将可复用的模板片段抽离成独立的模板文件: Extract frequently used template fragments (such as head, tail, navigation bar, etc.) into separate template files, which can improve the maintainability and reusability of the code.
  • 在需要的地方引入和调用: Use the ​{ {include}}​ tag to introduce other template files, and pass in the corresponding data for rendering. This avoids writing the same template code repeatedly.
    How to effectively organize and manage template files:

2. Organize template files reasonably

  • Store template files of different types or functions in appropriate directories for easy management and search.
  • 使用命名规范: Give the template file a meaningful name, which is convenient for developers to understand and call. Name it by page, module or function, etc.
  • 模块化开发: Split the template into smaller modules, so that each module has independent functions and responsibilities, which is convenient for independent maintenance and expansion.

3. Performance optimization

  • 增量渲染: If the amount of data is large, you can divide the template into multiple fragments, and only render part of the content that needs to be updated each time, instead of the entire template. This can reduce the workload of repeated rendering and improve rendering efficiency.
  • 缓存模板: Art-template supports template caching mechanism, caching is enabled by default. For templates that are rendered frequently and whose data is not updated frequently, the caching function can be enabled to reduce the overhead of compilation and rendering.
  • 减少 DOM 操作: When rendering large-scale data, minimize the number of direct DOM operations. You can use string concatenation or create a document fragment that is inserted into the DOM tree in one go at the end to improve performance.
  • 合理使用过滤器: Filters are the way data is processed and formatted. But be aware that filters incur additional computational overhead, so weigh the performance impact when using filters.

Guess you like

Origin blog.csdn.net/weixin_40845165/article/details/132182353