Mohawk / Template

    In this article, I will talk about the template engine that is used in the Mohawk JS framework.

    Why do you need templating?

    As in server scripts, the main task of the template engine is to separate the code from the presentation (for example, HTML markup), and in Java scripts it plays a similar role. Well, it also becomes more convenient to write code.

    Template Engine - Template


    The template code in the Mohawk is located in the kernel / Template.js file and is connected by default. The template engine itself is a Template object , in which we will use two methods:
    - void Template. assign (String name, mixed value)
    - String Template. transform (String template)

    As you can guess from the description, the first method assigns variables to the template engine, taking as arguments: the name of the variable and its value. Moreover, the value can be anything: a number, a string, an object, etc. The second method directly transforms the template and returns the result of the transformation.

    In the examples below, I will describe a very simple, but at the same time convenient template language. For the convenience of defining templates, I use the built-in function includeTemplate (name), which loads a file from the templates folder with the name name.tmpl and assigns the contents of the template to the NAME variable.

    Variable output

    So, the output of the given variable is carried out through the construction {% name}, where name is the name of the variable.
    Example:
    Template.assign('foo', 'bar'); // присваиваем переменной foo значение bar
    var str = Template.transform('foo is {%foo}'); // str = 'foo is bar'

    * This source code was highlighted with Source Code Highlighter.


    Let's try to present a specific example: we need to display the number of letters in the user's mailbox.
    Our template: var.tmpl

    You have {%num} emails



    * This source code was highlighted with Source Code Highlighter.


    Javascript:
    includeTemplate('var');
    Template.assign('num', 5);
    var str = Template.transform(VAR);

    * This source code was highlighted with Source Code Highlighter.


    Result (value of str variable ):

    You have 5 emails



    * This source code was highlighted with Source Code Highlighter.


    Condition

    The conclusion on the condition is carried out through the construction {% if condition} ... {% end}

    Example ( cond.tmpl ):
    {%if num > 0}
      

    You have {%num} emails


    {%end}

    * This source code was highlighted with Source Code Highlighter.


    Javascript (we already assigned the value to the variable num , so here we just continue):
    includeTemplate('cond');
    str = Template.transform(COND);

    * This source code was highlighted with Source Code Highlighter.


    The result will be similar to the previous example, because num = 5> 0:

    You have 5 emails



    * This source code was highlighted with Source Code Highlighter.


    Suppose that there are no letters in the box. Then we need two options for the template, which we will use in the presence of letters and their absence. To do this, we use the construction {% if condition} ... {% else} ... {% end}

    Example ( contra.tmpl ):
    {%if num > 0}
      

    You have {%num} emails


    {%else}
      

    Your mailbox is empty :(


    {%end}

    * This source code was highlighted with Source Code Highlighter.


    Javascript (change the value of the num variable to zero):
    includeTemplate('contra');
    Template.assign('num', 0);
    str = Template.transform(CONTRA);

    * This source code was highlighted with Source Code Highlighter.


    Result:

    Your mailbox is empty :(



    * This source code was highlighted with Source Code Highlighter.


    Cycles

    Move on. We need to display the contents of the mailbox. Let the content be eventually written to the emails array . To output the array to the table, we use the loop construction: {% for elem in array} ... {% end} - where elem is the element of the array and array is the array itself.

    First javascript:
    var emails = [
      {'from': 'boss@example.com', 'subject': 'When will you finish the project??'},
      {'from': 'me@example.com',  'subject': 'Reminder: finish the project'},
      {'from': 'spam@example.com', 'subject': 'You have WON 1000000 dollars!'}
    ];
    Template.assign('emails', emails);

    includeTemplate('loop');
    str = Template.transform(LOOP);

    * This source code was highlighted with Source Code Highlighter.


    Now the template ( loop.tmpl ):
    {%if emails.length > 0}
      

    You have {%num} emails



      
        
          
            
            
          
        
        
      {%for email in emails}
          
            
            
          
      {%end}
        
      
    FromSubject
    {%email.from}{%email.subject}


    {%else}
      Your mailbox is empty :(
    {%end}

    * This source code was highlighted with Source Code Highlighter.


    And finally, the result:
      

    You have 0 emails


      
        
          
            
            
          
        
        
      
          
            
            
          
      
          
            
            
          
      
          
            
            
          
      
        
      
    FromSubject
    boss@example.comWhen will you finish the project??
    me@example.comReminder: finish the project
    spam@example.comYou have WON 1000000 dollars!


    * This source code was highlighted with Source Code Highlighter.


    Suppose we need to display the address book. Let the book be written in the variable book , which is an associative array (hash) with the structure: key (person’s name) - value (email). To iterate the array not only by elements, but also by keys, we use the construction: {% for elem in array => key} ... {% end}.

    Example:
    var book = {
        'Alice': 'alice@example.com',
        'Bob': 'bob@example.com',
        'Carol': 'carol@example.com'
    };
    Template.assign('book', book);

    includeTemplate('loop2');
    str1 = Template.transform(LOOP2);

    * This source code was highlighted with Source Code Highlighter.


    Template ( loop2.tmpl ):

      
        
          
          
        
      
      
    {%for email in book => name}
        
          
          
        
    {%end}
      
    NameEmail
    {%name}{%email}


    * This source code was highlighted with Source Code Highlighter.


    Result:

      
        
          
          
        
      
      

        
          
          
        

        
          
          
        

        
          
          
        

      
    NameEmail
    Alicealice@example.com
    Bobbob@example.com
    Carolcarol@example.com


    * This source code was highlighted with Source Code Highlighter.


    Variable modifiers

    Well, and finally. For example, when outputting email. mail in the address book, we want to automatically turn it into a link. In order to modify a variable, the construction is used: {% name | function} - ie function function will be applied to the name variable .

    Last example:
    var linkify = function (email) {
      return '' + email + '';
    }

    includeTemplate('mod');
    str = Template.transform(MOD);

    * This source code was highlighted with Source Code Highlighter.


    Template ( mod.tmpl ):

      
        
          
          
        
      
      
    {%for email in book => name}
        
          
          
        
    {%end}
      
    NameEmail
    {%name}{%email|linkify}


    * This source code was highlighted with Source Code Highlighter.


    Result:

      
        
          
          
        
      
      

        
          
          
        

        
          
          
        

        
          
          
        

      
    NameEmail
    Alicealice@example.com
    Bobbob@example.com
    Carolcarol@example.com


    * This source code was highlighted with Source Code Highlighter.


    Finally


    The template engine allows you to organize the project code, as well as increase the speed of development.
    You can download the Mohawk here: irokez.org/download/mohawk
    A introductory article about the framework was here: habrahabr.ru/blogs/irokez_cms/53778

    Also popular now: