The Web template is there
Whether you use a template engine directly or not, Web templates are always there, either front end or back end. Even before the HTML standard was established.
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:
PHP (” PHP: Hypertext Preprocessor “, an acronym for Hypertext Preprocessor) is a widely used open source multipurpose scripting language that can be embedded in HTML, especially for Web development.
Repackaged template engines have cropped up many times in the PHP world, notably Smarty.
PHPer generally agrees that PHP itself is the most natural, native PHP template engine, because it is. Does Smarty need to exist?
Many other server-side languages have HTML template engines, such as JSP and Mustache.
Sure enough, the result of these server-side templating engines is HTML(XML) strings. The process logic is implemented using the host language’s own syntax.
Common features: HTML is just a string, and the end result may require a cleaning or corrective validation tool like Tidy.
Browser-side template engine
The earliest front-end template engine I know of is jCT, hosted in Google Code, which may not be accessible, in 2008. The host language is JavaScript and works in the browser. It is my honor to be the author of jCT, the related early blog Achun, Github jCT backup.
Until writing this article today, I did not realize that pure-JS also mentioned many pioneers, jemPlate was created at least in 2006.
Today you will get 100+ results in the OSC Search JavaScript template engine.
Common features: All support interpolation.
Everything else is very different, from different perspectives: too many to do all
- Lightweight tPL.js, T.JS
- Recognition 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
There’s also a comparison of templating- Engines popularity (you can add). Even best-javascript-Templating – Engines and the pros and cons.
How to choose
I think every engine, every framework has something to offer, at least in your application, at some point in time. So this article will not comment on the bad aspects of an engine, that would not be objective.
The following are general suggestions for engine selection, analyzing several issues for your application: step by step, filter by filter
- If you choose an engine that meets your data rendering needs and doesn’t conflict with existing dependencies, if you’re already familiar with an engine, you already have your answer.
- Is it a one-time project requirement? Choose the light and least complex ones
- Is it component development?
- The engine supports pre-compiled results, so don’t you have to compile them in real time every time?
- Cross-platform? There is official support, the preferred class of React-JSX engine or pure VDOM engine
- Choose the least complex to learn or maintain, as developers are notoriously averse to spending more time debugging than writing code
- Finally, performance comparison is a very delicate work, and other people’s comparisons may not match your scenario
I think the problem should be weakened: the comparison of grammatical styles, preferences are not comparable, some grammars even have special background reasons.
Now to answer the first question: Is There a need for Smarty? My answer: Yes. The reason is simple. It’s for whom. It’s for the context. For applications where there is no separation between the front end and the back end, or the front end person is not familiar with the back end language, or because of job responsibilities, it is realistic for the front end person to have a common template syntax (language). It would be a waste of skill for PHPer to use Smarty on his own.
Why is the performance comparison last?
Performance is important, but if it doesn’t affect the experience of your app, ignore it. It is difficult to simulate the real application scenario, usually only through the real scenario to check, the current testing tools can not hit this effect. If you find one, please recommend it. I need it too.
Some of the previous questions have fixed answers, but the remaining ones: how does component development compare to support for precompilation and complexity?
Component development
Component development is no longer a matter of choosing a template engine, it is an ecological choice. The reality is that your app needs to be done faster, timing is Paramount, choose popular frameworks, even if they offer enough components for you to use or reference right now. If your application has a separate ecosystem that requires technology selection for long-term maintenance, continue below.
precompiled
Precompilation should have:
- Compilation results no longer require compilation in the target environment.
- Compile results for debuggability, which means the results should contain native ECMAScript code rather than pure data descriptions.
React Without JSX, or React Without JSX.
Some engines based on string processing also support precompilation.
If you need to precompile, it is recommended to abandon the compiled engine which is still based on string concatenation, rather than precompile, which is the option before HTML5 is widely supported.
In addition, the extremely professional Polyfill. IO can solve 99% of your browser compatibility problems.
At the very least, a compilation like React-Jsx is required to be debuggable. Note: Vue.js supports multiple template engines to achieve the same effect
Original ReactJS code: Uses the concept of Web Components
class HelloMessage extends React.Component {
render() {
return <div>Hello <x-search>{this.props.name}</x-search>!</div>;
}
}Copy the code
The compiled:
class HelloMessage extends React.Component { render() { return React.createElement( "div", null, "Hello ", React.createElement( "x-search", null, this.props.name ), "!" ); }}Copy the code
Many VDOM engines can compile similar effects, such as HTMLtemplate-vdom.
<script>
var id = 3;
var env = {
people: [
{
id: 'id1',
name: 'John',
inner: [{ title: 'a1' }, { title: 'b1' }],
city: 'New York',
active: true
},
{
id: 'id2',
name: 'Mary',
inner: [{ title: 'a2' }, { title: 'b2' }],
city: 'Moscow'
}
],
githubLink: 'https://github.com/agentcooper/htmltemplate-vdom',
itemClick: function(id) {
env.people.forEach(function(person) {
person.active = String(person.id) === String(id);
});
loop.update(env);
}
// Omitted ....
};
</script>Copy the code
The complexity of the
It is difficult to judge which of the two engines is less complex by a single criterion. This is caused by the different thinking patterns of users. For example, the differences in engine usage and precompilation results outlined in the previous section will be felt differently by different users. This is the rationality and value of the existence of these different engines. The world is wonderful because of difference.
Some users think that the string template is sufficient for this application scenario and is lightweight enough. Some users feel that string concatenation's template engine is not strong enough or modern enough. Some users think OOP is rational, logical, and abstract. Some users think native HTML is a front end. Some users think VDOM is more versatile.Copy the code
Each of these judgments has its own reasons, and the criteria are different depending on the focus.
String-class templates are usually lightweight and beyond the scope of this section.
What are the common criteria for the complexity of non-string templates? I think you can take into account the complexity of data binding.
The data binding referred to in this article is not just interpolation, but also context and events, and even the hosting environment for the entire runtime.
In fact, you need at least a VDOM level engine to have this capability, because VDOM maps to real DOM nodes.
There are probably several patterns (combinations):
- The entry parameter is an Object, a variable in the template
x
Is of the object.x
Attribute. Example:virtual-stache-example - Specific syntax or attributes, such as vue.js
<a v-on:click="doSomething">... </a>
Attributes,computed
.methods
- Abstract semanticized properties, such as vue.js
active
This word can be used in a variety of situations and is easy to understand without ambiguity - It is not responsible for binding and requires the user to be very familiar with native methods to bind using native methods. For example: PowJS
These patterns are theoretical and are usually the problem for template engine designers to solve. It is better for users to simply ask:
- Is it possible to debug the simplest console.log(context) in an HTML template?
- Can you bind multiple DOM trees or pass different context parameters?
- Can generated nodes be accessed up the hierarchy of the DOM tree?
The template engine team will give you the correct solution, but it is often not the same as the literal goal of the problem. I think that’s what you’re going to judge your choices on, your acceptance of what the authorities say is the right approach.
Embed it in the DOM
Embed it in HTML
For historical reasons PHP is still a server-side hypertext preprocessor, and HTML is still a string in PHP. But:
HTML from the PHP perspective is a string, and PHP is really seamlessly embedded into the HTML “host”
In the WEB industry standards are perfect, the environment is greatly improved today, the front-end template engine can break through only embedded in HTML strings or embedded in VDOM, can not really
Embed it in the DOM
PowJS does this, and of course I’m the designer of PowJS. PowJS is implemented like this:
- Implement the directives that the template must implement
- Precompiled output native ECMAScript code
- Template syntax structure is consistent with ECMAScript function writing
Ultimately, writing PowJS templates is like writing ECMAScript functions.
GoHub index
<template> <details func="repo" param="data" if="is.object(data.content)&&! sel(`#panel details[sha='${data.sha}']`)" open let="ctx=data.content" sha="{{data.sha}}" origin="{{ctx.Repo}}" repo="{{data.owner}}/{{data.repo}}" subdir="{{ctx.Subdir||''}}" filename="{{ctx.Filename}}" render=":ctx" do="this.renew(sel(`#panel details[repo='${data.owner}/${data.repo}']`))" break > <summary>{{ctx.Description}}</summary> <div if="':';" each="ctx.Package,val-pkg"> <p title="{{pkg.Progress}}: {{pkg.Synopsis}}">{{pkg.Import}}</p> </div> </details> <dl func="list" param="data" if="! sel(`#panel details[sha='${data.sha}']`)&&':'||'';" each="data.content,data.sha,val-rep" do="this.appendTo(sel('#panel'))"> <details sha="{{sha}}" repo="{{rep.repo}}"> <summary>{{rep.synopsis}}</summary> </details> </dl> </template>Copy the code
The directives that appear in templates are familiar, and are the ones that most templates implement. There are also:
- Global object
is
.sel
- Template (function) naming
repo
.list
- Template (function) entry parameter
data
- Custom local variables
ctx
- Lower-level template (function) parameter derivation
data.sha
->sha
- Iterate over the value to the underlying template parameter derivation
(ctx.Package,val-pkg)
->pkg
;(data.content,val-rep)
->rep
- DOM node operation
this.renew
.this.appendTo
. This renders directly to the page DOM tree - Process control
break
- Pseudo node
if="':';"
Render time does not generate at alldiv
Node, which is a pseudo-node, equivalent to the block code symbol “{}”
Key: The entire template structure, directive semantics and ECMAScript functions are identical.
- There is no data binding, you are writing ECMAScript functions and passing parameters. What binding do you want
- There is no event binding, each node is real, just write addEventListener
- If you want to debug, just pick one
do
或if
或let
insert_=console.log(x),
Well, comma expressions insert almost seamlessly into any native statement - The exported view is ECMAScript source code, the following is taken from the demo My Folders
So is PowJS the ultimate choice?
The idea of PowJS is native, native DOM, native ECMAScript.
Native is also a problem with PowJS, not all users like native, I believe some users prefer a more abstract style, they always think of it as “primitive “.
My point remains:
Your needs are the key to choosing a template, and the world is wonderful because it is different
To promote friendship
Gohub
Golang-China