Skip to main content

Echo Template Functions

In the Echo templating system, template functions add powerful capabilities that go beyond simple data insertion. These functions allow you to transform data, make conditional decisions, format values, and implement various logic directly within your templates.

Introduction to Template Functions

Template functions in Echo provide ways to manipulate and transform data before it's displayed in your templates. They serve as little utilities that can be called within template expressions, allowing for dynamic content generation beyond simple variable placement.

A template function looks like this in Echo templates:

{{ functionName(parameters) }}

Where functionName is the name of the function and parameters are the values passed to the function.

Basic Template Functions

String Manipulation Functions

uppercase

The uppercase function converts a string to uppercase.

{{ uppercase("hello") }}

Output:

HELLO

lowercase

The lowercase function converts a string to lowercase.

{{ lowercase("HELLO WORLD") }}

Output:

hello world

trim

The trim function removes whitespace from the beginning and end of a string.

{{ trim("  hello world  ") }}

Output:

hello world

Numeric Functions

add, subtract, multiply, divide

These functions perform basic arithmetic operations.

{{ add(5, 3) }}
{{ subtract(10, 4) }}
{{ multiply(2, 6) }}
{{ divide(20, 5) }}

Output:

8
6
12
4

round

The round function rounds a number to the specified decimal places.

{{ round(3.14159, 2) }}

Output:

3.14

Conditional Functions

if

The if function allows you to conditionally include content based on a condition.

{{ if(isAdmin, "Admin Panel", "User Dashboard") }}

If isAdmin is true, it will output "Admin Panel", otherwise "User Dashboard".

defaultValue

The defaultValue function provides a fallback when a value is empty or null.

{{ defaultValue(user.nickname, user.name, "Guest") }}

This will use user.nickname if it exists, otherwise fall back to user.name, and finally to "Guest" if both are empty.

Working with Collections

join

The join function combines array elements into a single string.

{{ join(["Apple", "Banana", "Cherry"], ", ") }}

Output:

Apple, Banana, Cherry

length

The length function returns the number of elements in an array or characters in a string.

{{ length(["Red", "Green", "Blue"]) }}
{{ length("Hello") }}

Output:

3
5

Date and Time Functions

formatDate

The formatDate function formats a date according to a specified pattern.

{{ formatDate(user.joinDate, "YYYY-MM-DD") }}

Assuming user.joinDate contains a date value for January 15, 2023:

Output:

2023-01-15

timeAgo

The timeAgo function converts a timestamp to a human-readable "time ago" format.

{{ timeAgo(comment.timestamp) }}

For a comment posted 3 hours ago:

Output:

3 hours ago

Practical Examples

Example 1: User Profile Template

html
<div class="user-profile">
<h1>{{ uppercase(user.name) }}</h1>
<p>Member since: {{ formatDate(user.joinDate, "MMMM D, YYYY") }}</p>
<p>Bio: {{ defaultValue(user.bio, "No bio provided") }}</p>

<h2>Skills</h2>
{{ if(length(user.skills) > 0,
"<ul>" + join(map(user.skills, "<li>{it}</li>"), "") + "</ul>",
"<p>No skills listed</p>")
}}

<div class="user-stats">
<span>Posts: {{ user.postCount }}</span>
<span>Reputation: {{ round(user.reputation, 1) }}</span>
</div>
</div>

Example 2: Product Display with Discount Calculation

html
<div class="product-card">
<h2>{{ product.name }}</h2>
<div class="price-info">
{{ if(product.onSale,
"<p class='original-price'>$" + product.originalPrice + "</p>" +
"<p class='sale-price'>$" + round(multiply(product.originalPrice, subtract(1, product.discountPercent)), 2) + "</p>" +
"<p class='discount-tag'>" + round(multiply(product.discountPercent, 100), 0) + "% OFF</p>",
"<p class='regular-price'>$" + product.originalPrice + "</p>")
}}
</div>
<p>{{ if(product.inStock, "In Stock", "Out of Stock") }}</p>
<div class="ratings">
{{ join(repeat("★", round(product.rating)), "") }}{{ join(repeat("☆", subtract(5, round(product.rating))), "") }}
({{ product.reviewCount }} reviews)
</div>
</div>

Creating Custom Template Functions

Echo allows you to register custom template functions to extend functionality beyond the built-in options.

javascript
const echo = require('echo-templating');

// Register a custom function
echo.registerFunction('capitalize', (str) => {
if (typeof str !== 'string') return str;
return str.charAt(0).toUpperCase() + str.slice(1).toLowerCase();
});

// Using the custom function in a template
const template = 'Hello {{ capitalize(name) }}!';
const result = echo.render(template, { name: 'john' });
// Result: "Hello John!"

Best Practices for Using Template Functions

  1. Keep Templates Readable: While template functions are powerful, excessive nesting can make templates hard to read and maintain.

  2. Move Complex Logic to Code: If you find yourself writing very complex expressions with multiple nested functions, consider moving that logic to your JavaScript code instead.

  3. Create Custom Functions: When you find yourself repeating the same function combinations, create a custom function to simplify your templates.

  4. Document Custom Functions: If you create custom functions, document them well for other developers on your team.

  5. Consider Performance: Some complex function operations might impact performance if used extensively in large templates.

Summary

Echo template functions add a powerful layer of dynamic behavior to your templates, allowing for data transformation, conditional rendering, formatting, and much more. By combining these functions, you can create sophisticated templates while keeping your presentation logic separate from your application logic.

Functions fall into several categories:

  • String manipulation (uppercase, lowercase, trim)
  • Numeric operations (add, subtract, multiply, divide)
  • Conditional logic (if, defaultValue)
  • Collection handling (join, length, map)
  • Date formatting (formatDate, timeAgo)

Remember that while template functions are powerful, they should primarily be used for presentation logic. Complex business logic is better handled in your application code.

Exercises

  1. Create a template that displays a list of products with their prices, applying a 15% discount to products marked as on sale.

  2. Build a blog post template that shows the author's name, post date in "time ago" format, and truncates the content to 100 characters with an ellipsis if it's longer.

  3. Create a custom template function that converts a number to its ordinal form (1st, 2nd, 3rd, etc.) and use it in a template listing competition rankings.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)