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.
To run the program, save it as templates.cr and use the crystal command:
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.