Text Templates in Elixir

Our first program will demonstrate how to use text templates in Elixir. Here’s the full source code:

defmodule TextTemplates do
  import EEx

  def main do
    # We can create a new template and compile its body from a string.
    # Templates are a mix of static text and expressions enclosed in
    # <%= ... %> that are used to dynamically insert content.
    t1 = EEx.compile_string("Value is <%= @value %>\n")

    # By "evaluating" the template we generate its text with
    # specific values for its expressions.
    IO.write(EEx.eval_string(t1, assigns: [value: "some text"]))
    IO.write(EEx.eval_string(t1, assigns: [value: 5]))
    IO.write(EEx.eval_string(t1, assigns: [value: ["Elixir", "Rust", "C++", "C#"]]))

    # If the data is a map we can use the <%= @field_name %> syntax to access
    # its fields.
    t2 = EEx.compile_string("Name: <%= @name %>\n")

    IO.write(EEx.eval_string(t2, assigns: [name: "Jane Doe"]))
    IO.write(EEx.eval_string(t2, assigns: %{name: "Mickey Mouse"}))

    # if/else provide conditional execution for templates.
    t3 = EEx.compile_string("<%= if @value do %>yes<% else %>no<% end %>\n")
    IO.write(EEx.eval_string(t3, assigns: [value: "not empty"]))
    IO.write(EEx.eval_string(t3, assigns: [value: ""]))

    # Enum.map lets us loop through lists. Inside the loop, we can access
    # the current item of the iteration.
    t4 = EEx.compile_string("Range: <%= Enum.map(@list, fn item -> item <> " " end) %>\n")
    IO.write(EEx.eval_string(t4, assigns: [list: ["Elixir", "Rust", "C++", "C#"]]))
  end
end

TextTemplates.main()

To run the program, save it as text_templates.exs and use elixir:

$ elixir text_templates.exs
Value is some text
Value is 5
Value is ["Elixir", "Rust", "C++", "C#"]
Name: Jane Doe
Name: Mickey Mouse
yes
no
Range: Elixir Rust C++ C# 

This example demonstrates how to use text templates in Elixir using the built-in EEx (Embedded Elixir) module. EEx allows you to embed and evaluate Elixir expressions in strings.

Key points:

  1. We use EEx.compile_string/1 to compile template strings.
  2. EEx.eval_string/2 is used to evaluate compiled templates with specific values.
  3. Template expressions are enclosed in <%= ... %>.
  4. Conditional statements can be used with <%= if ... do %>...<% else %>...<% end %>.
  5. For loops can be implemented using Enum.map/2 within a template expression.

Elixir’s approach to templates is similar to other languages, allowing for dynamic content generation and customized output.