ECT templating JavaScript update released

    Exactly three months ago, I introduced the ECT templating engine to the JavaScript community . Yesterday, an update was released for him, which I want to talk about in this article.

    Do you know ECT?

    ECT is a JavaScript template engine with built-in CoffeeScript syntax (hence the name: Embedded CoffeeScript Templates). ECT was originally developed with a focus on maximum performance, and at the same time it provides the developer with a rich set of functions.

    What's new?


    Now ECT can be called the fastest JavaScript template engine . Under this item, work has been completed in the near future, as achieved the speed that was originally sought.

    Precompilation of templates on the server, before sending it to the client

    After the publication of ECT, I received many different reviews, both with criticism and with gratitude. There were reviews and suggestions. One of the most frequent suggestions was to add the ability to pre-compile templates on the server side so as not to load the rather heavy coffee-script.js on the client and improve client performance.

    Now such an opportunity has appeared. The compiler is implemented as middleware for connect / express.

    It works like this:
    • We configure a template engine on the server;
    • Add middleware template compiler to the stack of our connect / express application;
    • On the client, specify root as the root url that will serve middleware.

    When a client requests a template from the server, this request serves the middleware of the template compiler, and in response the client receives an already compiled template. In this regard, there is no need to connect the CoffeeScript compiler on the client side and at the same time, we do not have to compile templates manually after each change. The compiler will do everything himself.

    However, manual compilation may still come in handy. For example, to use a template engine without Node.JS as a server or with PhoneGap (with which ECT is very friendly). TODO has already entered the point of creating a utility for pre-compiling templates from the command line.

    Middleware example:

    var connect = require('connect');
    var ECT = require('ect');
    var renderer = ECT({ root : __dirname + '/views', ext : '.ect' }); // Настраиваем шаблонизатор. Здесь параметр root это путь к директории с шаблонами на диске.
    var app = connect()
       * Подключаем middleware компилятора шаблонов.
       * Тут параметр root обозначает base url, который будет обслуживать шаблонизатор.
       * Т.е. по url http://server:3000/views/page будет доступен скомпилированный шаблон из __dirname + '/views' + 'page.ect'
      .use(renderer.compiler({ root: '/views', gzip: true }))
      // Тут могут быть остальные middleware
      .use(function(err, req, res, next) {

    In the configuration of the template engine on the client, we must specify the same root as in the middleware configuration of the template compiler.

    var renderer = ECT({ root : '/views', ext : '.ect' });
    var data = { title : 'Hello, World!' };
    var html = renderer.render('template', data);

    Full express framework support

    Connecting ECT as a template engine in express is now no problem.

    var express = require('express');
    var app = express();
    var ECT = require('ect');
    var ectRenderer = ECT({ watch: true, root: __dirname + '/views' });
    app.engine('.ect', ectRenderer.render);
    app.get('/', function(req, res){
    console.log('Listening on port 3000');


    Added the ability to synchronously call the render method.

    This slightly improves performance when errors are caught centrally, for example using connect-domain, and gives freedom to choose the style of writing code.

    Asynchronous style:

    var renderer = ECT({ root : '/views' });
    var data = { title : 'Hello, World!' };
    renderer.render('template.ect', data, function (err, html) {

    Synchronous style:

    var renderer = ECT({ root : '/views' });
    var data = { title : 'Hello, World!' };
    var html = renderer.render('template.ect', data);

    It is worth noting that both options are performed synchronously . The only difference is in the writing style and that the first option passes an error to callback, and the second, in case of an error, makes a throw. The second option works a little faster.

    Added support for multi-line expressions.

    Although I myself do not really like the idea of ​​writing helpers inside templates, this feature was asked quite often ( eco issues were also asked to add this feature in issues of the templating engine ), so it was decided to implement it.

    Now you can define small functions in the template code or execute other code.


    truncateHelper = (str) ->
      if str.length > 10
        return (str.substr 0, 10) + '…'
        return str
    <%- truncateHelper @title %>

    For dessert

    For ECT, a syntax highlighting plugin for the Sublime Text 2 editor has been released . Special thanks to TurtlePie for it .

    Also popular now: