JavaScript technologies

UI templates

Horváth, Győző
senior lecturer
horvath.gyozo@inf.elte.hu

Financed from the financial support ELTE won from the Higher Education Restructuring Fund of the Hungarian Government

Template management

Abstraction for generating HTML

Basic concepts

  • string concatenation is wrong (for this purpose)
    • erroneous, verbose, slow
  • separation of HTML structure from the processing logic
  • template: the required HTML structure with placeholders
  • dynamic content
  • reusable with different data

Template languages and engines

  • Jade
  • Mustache
  • Handlebars
  • Haml
  • EJS
  • Plates
  • Pure

Example

Concatenation

function createListItem(book) {
    return '<li><a href="show/' + book.id + '">' + 
        book.title + '</a></li>';
}

Example

<script id="listItem" type="text/template">
    <li>
        <a href="show/<%= id %>"><%= title %></a>
    </li>
</script>
//Getting the template string
var templateString = $('#listItem').html();

//Compiling the template
var compiledTemplate = _.template(templateString);

//The data
var book = {
    id: 12,
    title: 'JavaScript Patterns'
};

//Generating HTML string
var htmlString = compiledTemplate(book);

//Inserting HTML string to the document
$('#viewWrapper').html(htmlString);

Task

In the previous application generate the list items with a template!

Underscore

https://cdnjs.cloudflare.com/ajax/libs/underscore.js/1.8.3/underscore-min.js

The template

<script id="listItems" type="text/template">
    <% titles.forEach(function (e) { %>
        <li class="list-group-item"><%= e %></li>
    <% }) %>
</script>

UI logic

deleting makeListItemsFromArray

class ListView {
    constructor(props) {
        /* ... */
        this.template = _.template( $('#listItems').html() );
        /* ... */
    }
    onKeyUp(e) {
        /* ... */
        $('#code-list').html(this.template({ 
            titles: filteredTitles 
        }));
    }
}