Text Templates in Crystal

Crystal offers built-in support for creating dynamic content or showing customized output to the user with the ECR (Embedded Crystal) module. ECR allows you to embed Crystal code within text, which is then evaluated and replaced.

require "ecr"

# We can create a new template and parse its body from a string.
# Templates are a mix of static text and Crystal code enclosed in
# <%= ... %> that are used to dynamically insert content.
t1 = ECR.render("Value is <%= value %>\n")
puts t1.render(value: "some text")
puts t1.render(value: 5)
puts t1.render(value: ["Crystal", "Ruby", "Python", "JavaScript"])

# If the data is a struct or a named tuple, we can access its fields directly.
person = {name: "Jane Doe"}
t2 = ECR.render("Name: <%= person[:name] %>\n")
puts t2.render(person: person)

# The same applies to hashes; with hashes there is no restriction on the
# case of key names.
person = {"Name" => "Mickey Mouse"}
puts t2.render(person: person)

# if/else provide conditional execution for templates.
t3 = ECR.render("<%= value ? "yes" : "no" %>\n")
puts t3.render(value: "not empty")
puts t3.render(value: "")

# Each blocks let us loop through arrays or other enumerable objects.
t4 = ECR.render("Range: <% value.each do |item| %><%= item %> <% end %>\n")
puts t4.render(value: ["Crystal", "Ruby", "Python", "JavaScript"])

To run the program, save it as templates.cr and use the crystal command:

$ crystal templates.cr
Value is some text
Value is 5
Value is ["Crystal", "Ruby", "Python", "JavaScript"]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Crystal Ruby Python JavaScript 

In Crystal, we use the ECR (Embedded Crystal) module for templating, which is similar to ERB in Ruby. The syntax is slightly different from Go’s text templates:

  • Instead of {{...}}, we use <%= ... %> for expressions that should be output.
  • For control structures that don’t output directly (like if or each), we use <% ... %>.
  • The ECR.render method is used to create and render templates.
  • Crystal uses symbols (:name) or string keys for accessing hash/named tuple values.

Crystal’s ECR is compiled at compile-time, which makes it very efficient. It’s primarily used for generating HTML in web applications, but can be used for any text templating needs.