Understanding and exploring embedded elixir
Embedded Elixir allows us to embed Elixir code inside a string in a consistent and robust way, outlined by the EEx
package. This further allows us to write templates that can be dynamically evaluated using Elixir.
EEx
makes the following code possible:
$ iex iex> string = "Hello <%= @person %>" "Hello <%= @person %>" iex> EEx.eval_string(string, assigns: [person: "World"]) "Hello World"
In the preceding code snippet, we were able to add the ability to evaluate an otherwise static string dynamically using Elixir. In the string, anything inside the <%
and %>
tags is evaluated as Elixir. Therefore, if we have the variables or functions in the context of evaluation, inside those tags they will get evaluated on calling EEx.eval_string/3
. Here’s an example where we evaluate a function inside a string using embedded Elixir:
$ iex iex> string = "Hello <...