Template Engine

28 Feb 20223 minutes to read

Syncfusion ASP.NET MVC (Essential JS 2) has built-in template engine which provides options to compile template string into a executable function. Then the generated executable function can be used for rendering DOM element using desired data.

Compiling

compile method from ej2-base can be used to convert our template strings into executable functions.

<div id="element"></div>

<script>

    // data
    var data = { name: 'Aston Martin' };

    // Compiling template string into executable function
    var getDOMString = ej.base.compile('<div>${name}</div>');

    // Using generated function to get output element collection
    var output = getDOMString(data);

    // append html collection to element
    document.getElementById('element').appendChild(output[0]);

</script>

Available Template Syntax

Name Syntax Description
Expression <div>${name}</div> We have expression evolution as like ES6 expression string literals.
Dot Variable Access <div>${person.info.name}</div> Access the json variable with dot notation.
Variable Function <div>${name.toUpperCase()}</div> Utilize the variable function example, name.toUpperCase()
Window Function <div>${getCurrentTime()}div> Use window function inside template. > Here, getCurrentTime() is a function that defined in the window object.
Custom Helper Function <div>${covertToCurrency()}div> Use function that passed in helper function.
IF Else Statement <div>
${if(gender===”male”)}
<span class=’ico-male’>Male</span>
${else}
<span class=’ico-female’>Female</span>
${/if}
</div>
Branching statement in Template.
For Statement <div>
${for(mark of marks)}
<span>${mark}</span>
${/for}
</div>
Use for looping inside template.
For Index value access <div>
${for(mark of marks)}
<span>${markIndex}</span>
${/for}
</div>
Get the index value of item while using for statement. Use the variable Index that suffixed with loop item name.

Custom Helper

Custom helper function can be defined and passed to compile function. Refer to the following example.

<div id="element"></div>

<script>

    var customHelper = {
            upperCase: function upperCase(str) {
            return str.toUpperCase();
        }
    };

    var data = { name: 'Aston Martin' };

    var getDOMString = ej.base.compile('<div>${upperCase(name)}</div>', customHelper);

    let opElem = getDOMString(data);
    
    document.getElementById('element').appendChild(opElem[0]);

</script>