How to choose a web front-end template engine (recommended)

不言
Release: 2018-10-17 15:14:36
forward
4224 people have browsed it

The content of this article is about how to choose a Web front-end template engine (recommended). It has certain reference value. Friends in need can refer to it. I hope it will be helpful to you.

The template engine is responsible for assembling data and presenting the data in another form or appearance. The page in the browser is the final expression of the web template engine.

Whether you use the template engine directly or not, Web templates have always been there, not on the front end but on the back end. Its emergence can even be traced back to before the formal establishment of the Hypertext Markup Language HTML standard.

Server-side template engine

The earliest Web template engine I know of is PHP, which was officially born in 1997 and works on the server side. Let's take a look at PHP's official intro-whatis:

HPers generally agree that PHP itself is the most natural and native PHP template engine, because it is. There have been many repackaged template engines in the PHP world, the famous one being smarty.

Many other server-side languages ​​have HTML template engines, such as JSP and mustache.

There is no doubt that the final result generated by these server-side template engines is an HTML (XML) string, and the processing flow logic is implemented using the syntax of the host language itself.

Their common characteristics: HTML is just a string, and the final result may require cleaning or correction validation tools like Tidy.

Here is a question: Is it necessary to have secondary encapsulated smarty?

Browser-side template engine

The earliest one I know of The front-end template engine is jCT, which is hosted on Google Code and was born in 2008. The host language is JavaScript and works in the browser.

Search for JavaScript template engine in OSC today and you will get 100 results. Here are some:

Lightweight: tpl.js, T.js
Awareness: arttemplate, mustache .js, doT.js, handlebars.js, pug
DOM-tree-based: domTemplate, transparency, plates
VDOM-based: htmltemplate-vdom, virtual-stache, html-patcher
Popular frameworks: Vue.js, ReactJS, riot
Real-DOM: PowJS

Their common feature: all support interpolation.

There is also a comparison of the popularity of templating-engines, and even best-javascript-templating-engines voting and reasons for the pros and cons.

How to choose

I think existence is reasonable. Every engine and framework always has merits, at least in your application and in a certain era, so This article will not comment on what is bad about a certain engine, as that would be unobjective. Now to answer the question mentioned earlier: Is smarty necessary to exist? My answer is: yes. The reason is very simple, it depends on who it is used for and the overall background. For applications where the front-end and back-end are not separated, or the front-end personnel are not familiar enough with the back-end language, or due to job responsibilities, it is realistic for the front-end personnel to master a more common template syntax (language). On the contrary, let PHP use smarty by itself. It's such a waste of skills.

The following are general suggestions for engine selection:

The premise is that the selected engine can meet the data rendering needs and does not conflict with existing dependencies. If you are already very familiar with an engine, Then you already have your answer.

Is it a one-time project requirement? If so, just choose the lightweight one with the lowest learning complexity. Do you want to do component development?

The engine supports pre-compiled results, so you don’t have to compile them in real time every time?

Do you want to be cross-platform? There are official ones that provide support, and React-JSX is preferred. engine or a pure VDOM engine.

Choose the one with the lowest complexity to learn or maintain. As we all know, developers hate spending more time debugging than writing code.

The last step is performance comparison. Performance comparison is a very detailed task, and other people’s comparison results may not necessarily match your scenario.

I think the comparison of grammar styles should be weakened. Preferences are not comparable. Some grammars even have special background reasons.

Why is the performance comparison the last thing?

Performance is indeed important, but if performance has not affected your application experience, then ignore it. It is difficult to truly simulate application scenarios. Usually, it can only be tested through real scenarios. Current testing tools cannot achieve this effect.

Some of the aforementioned questions have fixed answers. Let’s discuss the remaining questions: How to consider component development, support for pre-compilation, and complexity?

Component Development

Component development is no longer a matter of choosing a template engine, it is a matter of ecological environment selection. If your application needs to be completed faster, then time is the first priority, choose a popular framework that has enough components for you to use or refer to. If your application has an independent ecological environment and requires technology selection for long-term maintenance, then continue reading below.

Pre-compilation

Pre-compilation should have:

The compilation result no longer requires a compilation process in the target environment.
Compile results for debuggability, which means that the results should contain native ECMAScript code rather than pure data descriptions.
Everyone knows that React-JSX supports pre-compilation. The official statement is that React Without JSX means it is always built.

Some string processing-based engines also support precompilation. If you need pre-compilation, it is recommended to abandon the engine whose compilation result is still based on string concatenation. It is better not to pre-compile. That was a technical method before HTML5 was widely supported.

At least there must be a compilation result similar to React-JSX to be debuggable. Note: Vue.js supports multiple template engines to achieve the same effect.

Original ReactJS code, which uses Web Components technology:

class HelloMessage extends React.Component {
  render() {
    return <p>Hello <x-search>{this.props.name}</x-search>!</p>;
  }
}
Copy after login

After compilation:

class HelloMessage extends React.Component {
  render() {
    return React.createElement(
      "p",
      null,
      "Hello ",
      React.createElement(
        "x-search",
        null,
        this.props.name
      ),
      "!"
    );
  }
}
Copy after login

Many VDOM engines can also compile similar effects, such as htmltemplate-vdom.

  <script>
        var id = 3;
        var env = {
            people: [
                {
                    id: &#39;id1&#39;,
                    name: &#39;John&#39;,
                    inner: [{ title: &#39;a1&#39; }, { title: &#39;b1&#39; }],
                    city: &#39;New York&#39;,
                    active: true
                },
                {
                    id: &#39;id2&#39;,
                    name: &#39;Mary&#39;,
                    inner: [{ title: &#39;a2&#39; }, { title: &#39;b2&#39; }],
                    city: &#39;Moscow&#39;
                }
            ],
            githubLink: &#39;https://github.com/agentcooper/htmltemplate-vdom&#39;,
            itemClick: function(id) {
                env.people.forEach(function(person) {
                    person.active = String(person.id) === String(id);
                });
                loop.update(env);
            }
            // Omitted ....
        };
    </script>
Copy after login

Complexity

It is difficult to use a single criterion to judge which of the two engines is less complex. This is caused by the different thinking patterns of users. For example, the differences in use and precompiled results of the engines listed above are different for different users. This is the rationality and value of the existence of different engines.

Some users think that string templates can meet the needs of this application scenario and are lightweight and sufficient.
Some users think that the template engine of string splicing technology is not powerful enough and not modern enough.
Some users think OOP is rational enough, logical enough, and abstract enough.
Some users think that native HTML is called front-end.
Some users believe that VDOM has wider applicability.

These judgments have their own reasons, with different focus and different standards. But we can still consider their complexity from their commonalities.

String class templates are usually very lightweight and are beyond the scope of this section. What are the common criteria for judging the complexity of non-string templates? I think the complexity of data binding can be considered.

The data binding referred to in this article is not just interpolation, but also includes context and events, and even the host environment of the entire runtime.

In fact, an engine that reaches at least the VDOM level is required to have this capability, because VDOM can be mapped to real DOM nodes.

There are probably several modes (combinations):

1. The entry parameter is an Object, and the variable x in the template is the .x attribute of the object, for example: virtual-stache-example
2. Specific syntax or attributes, such as: Vue.js's..., attributes computed, methods
3. Abstract semantic attributes, such as: Vue.js's active. The word active is suitable for a variety of scenarios and is easy to understand. And there is no ambiguity
4. It is not responsible for binding. Users need to be very familiar with native methods and use native methods for binding, such as: PowJS

These modes are only theoretical and are usually template engine designs. problem to be solved. For users, it is better to ask directly:

1. Can the simplest console.log(context) be written directly in the HTML template for debugging?
2. Can it be bound in a multi-layer DOM tree? Or pass different context parameters?
3. Can the generated Node be accessed upward in the multi-layer DOM tree?

The template engine team will give you the correct solution, but usually it is related to the problem Literally described goals vary. I think this is the key to your judgment of choice, your recognition of the correct method given by the official.

Embedded into DOM

Embedded into HTML

PowJS is implemented like this:

Instructions that must be implemented to implement the template
Pre-compiled Output native ECMAScript code
The template syntax structure is consistent with the writing method of ECMAScript functions
In the end, writing PowJS templates is like writing ECMAScript functions.

Writing in GoHub index

<template>
  <details>
    <summary>{{ctx.Description}}</summary>
    <p>
      </p>
<p>{{pkg.Import}}</p>
    
  </details>
  <dl>
    <details>
      <summary>{{rep.synopsis}}</summary>
    </details>
  </dl>
</template>
Copy after login

Most template engines will implement if and each instructions. The above PowJS template also has:

Global objects is, sel
Template (function) naming repo, list
Template (function) entry parameter data
Customized local variable ctx
Lower template (function) parameter derivation data.sha->sha
Traversal The value is deduced to the lower template parameter (ctx.Package,val-pkg)->pkg, (data.content,val-rep)->rep
DOM node operation this.renew, this.appendTo, this is directly Rendering to the page DOM tree
Process control break
Pseudo node if="':';", the p node is not generated at all during rendering. It is a pseudo node, equivalent to the block code symbol "{}"
The key is that the entire template structure, instruction semantics and ECMAScript functions are exactly the same:

There is no data binding, you are writing an ECMAScript function, just pass the parameters, what binding do you want?
There is no event binding, every All nodes are real, just write addEventListener directly
To debug, just find a do or if or let and insert _=console.log(x), that’s it. The comma expression can be inserted almost seamlessly All native statements
All business logic is written by the user himself, PowJS is only responsible for gluing them into a function
The exported view is the ECMAScript source code, the following picture is taken from the demo My Folders

How to choose a web front-end template engine (recommended)

So is PowJS the final choice? The concept of PowJS is nativeness, native DOM, and native ECMAScript.

Native is also the problem with PowJS. Not all users like native. I believe that some users prefer a more abstract style. In their eyes, native is always a bit "original".

Native means that you can extend and introduce other libraries for matching, but PowJS will never have a watcher implemented by define setter/getter, which is beyond the scope of the template engine. If there is, it must be an independent project.

Finally, my point is still: your needs are the key to choosing a template, and the one that suits you is the best.

The above is the detailed content of How to choose a web front-end template engine (recommended). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:segmentfault.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template