High performance Cross-language template engine Crox

Source: Internet
Author: User
Tags php language

http://thx.github.io/crox/

    • Crox is a high-performance cross-language template engine implemented by the JavaScript language . The Crox template can be used directly in JavaScript environments or as a source template for other programming languages such as php,jsp or other template engines, such as Velocity,smarty, and Crox will ensure the best execution efficiency of the translated results.

    • In the production system, we use a variety of front-end template engine has its own unique side, and Crox features that it is oriented to "cross-language and high-performance" The goal of the design, Crox's design process is the process of making a unique trade-off between the template-provided functionality and the target business type supported by the template, and ultimately confirming the template API.

    • At the implementation level, Crox is one of the many compiled template engines based on syntax analysis. Through strict API design, it is ensured that all kinds of code logic is simple and clear, which ensures high performance in multi-language environment. While Crox syntax is Kissy xtemplate or crox+ under certain conditions (developing And more powerful front-end template engine syntax, which allows the Crox API to be consistently extended and enhanced in the face of more complex, but purely front-end scenarios.

1 Technical Background 1.1 All-end ERA multiple web architectures will term coexistence
    • With the full spread of wireless services, presentation end development into the full-end era, a business often need to support both PC and mobile browser, as well as iOS and Android and other native development framework, the presentation of the diversity of the service-side interface to the pure data direction.

    • As far as the Web front end is concerned, there is an increasing number of rendering HTML structures based on the back-end pure Data interface (typically webapp based on single-page application technology), regardless of the PC or mobile side, whereas the traditional backend rendering HTML architecture remains long-standing.

    • We look forward to finding or building an efficient templating system that can uniformly describe the logic generated by the HTML structure so that it has consistent output in either the front-end or the back-end. This allows page component blocks in different front-end architectures to share reuse You can also easily solve the problem of single page application content cannot be indexed by the search engine.

2 Requirements Analysis 2.1 existing scenarios for consistent rendering at the front and back ends
    • NodeJS: Back-end introduction of NodeJS, let JS assume rendering work, so you can use any JS-based template, to achieve consistency.
    • Mustache: A logic-less template engine that is widely used in the front-end to achieve cross-language goals by providing runtime parsing libraries for various languages.
2.2 Feasibility analysis of existing schemes
    • The introduction of the NODEJS scheme requires a drastic transformation of the service side, and the introduction of node service undoubtedly increases the complexity and operational difficulty of the system, and the possibility of reconstructing the core production system in a short time is almost 0.
    • The introduction of mustache is a little better, but mustache itself still has a lot of problems.
      • First, Logic-less's mustache the business logic into the data, which requires that the input data often requires a lot of preprocessing, and the template ability is too simple, in the face of a slightly complex structure is inadequate.
      • Second, mustache provides template rendering services by providing runtime parsing libraries for different languages, such as the need to introduce mustache.php and instantiate the Mustache template engine in PHP ("$m = new mustache engine;") After use. Mustacheengine performance is very good, but because mustache syntax can not distinguish between if,else and clear data location , objectively still can not be compared with the pure PHP language determined choice or cycle, In production environments where performance requirements are extremely demanding, they are still not used smoothly.
2.3 Technical Goals

Combining the previous analysis, we need a template scheme that supports both front-and back-end rendering in a variety of architectures. That is, we need a high-performance cross-language template engine , which we named Crox. 3 Design and Implementation Overview 3.1 guaranteed performance through logical "literal translation"

Implementing Crox's cross-language features requires an offline translator rather than the middle tier of the runtime, so that the source template will generate a function based on the native javascript,php language after translation. Through the logical literal translation, the generated function has good readability and guarantees execution performance, here is an example:

JSON data:

{  "name": "Chris",  "value": 10000,  "taxed_value": 10000 - (10000 * 0.4),  "in_ca": true}

Crox templates:

你好 {{root.name}} 你刚赢了 ¥{{ root.value}}{{#if root.in_ca}}    嗯,税后 ¥{{ root.taxed_value}}{{/if}}

Post-translation JavaScript functions:

function (root) {    // 忽略$htmlEncode源码    var $s = ‘‘;    $s += "你好 ";    $s += $htmlEncode(root.name);    $s += " \n你刚赢了 ¥";    $s += $htmlEncode(root.value);    $s += "\n";    if (root.in_ca) {        $s += "\n    嗯,税后 ¥";        $s += $htmlEncode(root.taxed_value);        $s += "\n";    }    return $s;}

Translated php file content:

你好 <?php echo crox_encode($crox_root->name);?> 你刚赢了 ¥<?php echo crox_encode($crox_root->value);?><?php if($crox_root->in_ca){?>    嗯,税后 ¥<?php echo crox_encode($crox_root->taxed_value);?><?php }?>

It can be seen whether it is translated into JavaScript or PHP, the appearance of the code after the translation and people read the template when the intuitive impression of the same, encountered a judgment is a judgment, encountered a loop is a loop, each time the output of what data is very clear, and the code written by hand. " let's make it clear that the performance cost of each line of code is adequate and necessary.

Xtemplate the translated JavaScript function:

function (scope,s,undefined) {var buffer = "", config = this.config, engine = This, modulewrap, utils = config.utils;    if (typeof module!== "undefined" && module.kissy) {modulewrap = module;    } var runblockcommandutil = Utils.runblockcommand;    var getexpressionutil = utils.getexpression;    var getpropertyorruncommandutil = Utils.getpropertyorruncommand;    Buffer + = ' Hello ';    var id0 = Getpropertyorruncommandutil (engine, scope, {}, "Root.name", 0, 1, undefined, false);    Buffer + = Getexpressionutil (ID0, true);    Buffer + = ' You just won the ¥ ';    var id1 = Getpropertyorruncommandutil (engine, scope, {}, "Root.value", 0, 2, undefined, false);    Buffer + = Getexpressionutil (Id1, true);    Buffer + = ' \ n ';    var config2 = {};    var params3 = [];    var id4 = Getpropertyorruncommandutil (engine, scope, {}, "Root.in_ca", 0, 3, undefined, true);    Params3.push (ID4);    Config2.params = PARAMS3;        Config2.fn = function (scope) {var buffer = ""; Buffer + = '\ n Well, after-tax ¥ ';        var id5 = Getpropertyorruncommandutil (engine, scope, {}, "Root.taxed_value", 0, 4, undefined, false);        Buffer + = Getexpressionutil (ID5, true);        Buffer + = ' \ n ';    return buffer;    };    Buffer + = Runblockcommandutil (engine, scope, CONFIG2, "if", 3); return buffer;}

The above is Kissy xtemplate the same logic compiled functions, in fact, the code is not so much, there are many external methods to rely on. The reason is xtemplate compatible mustache, compatible handlebars provides a lot of accessibility. Such translation results in the front , each user's browser to run, its consumption can be completely ignored, but once transferred to the thousands of QPS (Query Per Second) of the back end, immediately become not to be ignored.

Therefore, only "literal translation" can guarantee the high performance of cross-language, if you want to achieve "literal translation", the necessary functional choice is the most important design. 3.2 The feasibility of "literal translation" through functional choice

The implementation of the front-end template engine is generally divided into two categories, through regular matching or through the analysis of syntax, crox because of the need for multi-lingual translation, it is necessary to adopt a syntax-based analysis of the scheme . At the same time there are different languages, crox need to be simple and clear logic, In this way, you can avoid too much uncertainty when you do translation. So there is a need to do more functional tradeoffs than other template engine Crox. We use the following example to illustrate Croxapi design ideas:

JSON data:

{    string : "a",    list : [        {},        {string : "b"}    ]}

Mustache Templates:

{{#list}}{{string}} {{/list}}

The string value in the current item is looked up in the loop of the mustache template, and if none continues to look in the outer data object, the final output is "a B". But such an outward lookup logic is bound to introduce a lot of code to the cost of completion, and eventually add up to become a performance problem. Crox avoids these consumption by explicitly specifying where to access the data

Crox templates:

{{#each root.list ‘val‘}}{{root.string}} {{val.string}} {{/each}}

The output of the above template is "a undefined b a", that is, using {{root.string}} when you need to access the outermost string value, you need to access the string in item, Access {{val.string}} with the TEMP variable val, The position of the output in the data is very clear. Based on a similar cause xtemplate ". /"To access data in the relative hierarchy is also not supported.

The following is an introduction to the Crox Basic API design baseline principles that have been repeatedly weighed. 3.3 Crox Basic API design principles

    • Root represents the input data object, except that in the loop, all the data locations to be accessed need to write the complete path from root.
    • Supports and explicitly distinguishes between branch statements (if) and circular statements (each)
    • In each, you need to explicitly specify a temporary variable name that is used to refer to the current element in the loop array and the current index
    • Supports simple judgment expressions and calculation expressions
    • Support for child template introduction
    • supports only the functions described above
3.4 API Features limited Crox trial range

While Crox supports a large number of common template features, Crox does not cover all of the features covered by many front-end template engines such as Xtemplate,handlebars,ejs. We look at the problem this way:

    • Complex page chunks are often accompanied by complex interactions that do not need to be exported from the backend to the page's underlying HTML. For example, clicking on the popup calendar component, just by the front-end real-time build is enough, you can change the other front-end template engine to complete the task.
    • If the Crox syntax can be a more powerful subset, you can quickly reach the goal by extending the syntax when you need to handle complex processing, and the next section describes the design of the two extension scenarios.

In combination with the above considerations, the Crox template is best suited to deal with the HTML construction of a page display block with less complex interactions , which guarantees good performance in both front-and back-end rendering. 3.5 Crox solutions for complex scenarios 3.5.1 Crox has been xtemplate included

In the latest version of Xtemplate already contains crox all the syntax, often use Xtemplate's pro, welcome to familiarize yourself with the next crox a few conventions to try Crox it. 3.5.2 Full-featured front-end template engine crox+ without parsing

The crox+ in the plan is a full-featured front-end template engine similar to the EJS syntax, where the logical part of the template can write arbitrarily complex JS code. Another feature of the crox+ is that it relies on simpler regular matching to complete the template parsing task, rather than having to parse the parsing execution.

The current Crox grammar is similar to the mustache style, in order to eliminate the grammatical analysis link, crox+ grammar style will change, of course crox is convenient to translate crox template into a template crox+ the specified style. 4 Summary

Crox is a cross-language high-performance template engine, the trick to ensure the performance is to ensure that the template logic in various languages can be "literal translation", in order to achieve this goal, Crox the template syntax is more strict conventions.

By using Crox, you can generate logic for page chunks, maintain consistency and ease in the products of the various architectures on the front and back, so that the components you develop can be more commonly accumulated and shared.

Crox syntax has been xtemplate compatible, if you are familiar with xtemplate, simply change a few coding habits, you can enjoy the convenience of crox. And when you feel that Crox is out of reach, Xtemplate will continue to help you do what you want. 5 Future

    • Add more translation goals.
    • With the help of Crox's full parsing of templates, the automation of local refresh of templates is facilitated.
    • In-Project template batch offline compilation tool.

    High performance Cross-language template engine Crox

    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.