Functions allow using a certain fragment of the code multiple times without describing it again. Declare the function (i.e. describe a fragment of code) only once and then call the function by its name.
Example
The rusdate function is described in the built-in template. The code of this function changes the numerical value of a month into a character value:
<% function rusdate(date) { %> // This function changes a numerical value of a month into a character value
<% if (!date || date == '') { return; }%> // If the date is not specified or it is empty, an empty value will be returned
<% var c = date.split(' ')[0].split('-'); %> // The data in the format DD-MM-YYYYY will be divided
<% month = {
'01': 'January',
'02': 'February',
'03': 'March',
'04': 'April',
'05': 'May',
'06': 'June',
'07': 'July',
'08': 'August',
'09': 'September',
'10': 'October',
'11': 'November',
'12': 'December'
} %>
<%= c[2] %> <%= month[c[1]] %> <%= c[0] %> г. // A numeracal value of MM will be changed into a month
<% } %>
This function is called in several sections of the template:
<div class="header">Invoice <%= payment.number %> from <% rusdate(payment.createdate) %></div>
Payment for <% if (payment.$postpay && payment.$postpay != 'on') { %> advance<% } %> payment N <%= payment.number %> from <% rusdate(payment.createdate) %>
Describing a custom function
As an example, let's create a function to say thank you to customers who make an order for more than 1 000 euro. The function code:
<% function opt(data) { %> //Declaration of the function. The function name is "opt".
<% var u = ''; %> // Declaration of the empty variable.
<% if (data > 1000 ) { %> //A condition to check the result.
<% u = 'Thank you, the amount:' + data; %> // Set the variable value.
<% return u; %> // Return the result to the template engine.
<% } %>
else {
<% u = data; %> } // Do not add "Thank you" if the total amount is less than 1 000 euro.
<% return u; %>
<% } %>
After you have added the function, add its call into the description of the string "Total":
<!-- Total -->
<tr class="total">
<td class="desc">Total</td>
<td class="amount"><%= payment.paymethodamount %></td>
</tr>
<% if (payment.taxrate) { %>
<tr class="total">
<td class="desc">VAT included<%=number_format(payment.taxrate,'0', '.', '')%>%</td>
<td class="amount"><%= opt(payment.paymethodamount) %></td> // Call of the opt. function. payment.paymethodamount is used as an example
</tr>
<% } %>
<!-- Total -->
After the invoice template code is changed, the document will show different information depending on the order amount.