Mau.MapDirectives (mau v0.8.0)

View Source

Handles special directives for render_map functionality.

Directives are special map keys that start with "#" and provide advanced map transformation capabilities.

Supported Directives

  • #pipe - Thread data through a series of transformations (like Elixir's |> operator)
  • #map - Iterate over a collection and apply a template to each item
  • #flat_map - Map over a collection and flatten the results into a single list
  • #merge - Merge multiple maps together
  • #if - Conditional rendering based on a boolean condition
  • #case - Pattern matching on values (like Elixir's case)
  • #cond - Condition-based branching (like Elixir's cond)
  • #filter - Filter items in a collection based on a condition
  • #pick - Extract specific keys from a map (similar to Map.pick)

Easy Extension

To add a new directive:

  1. Add a pattern match in match_directive/1
  2. Implement the corresponding apply_*_directive/3 function

Summary

Functions

Applies a directive to a map with the given context and rendering function.

Checks if a map contains a directive and returns the directive type and arguments.

Functions

apply_directive(arg, context, opts, render_fn)

Applies a directive to a map with the given context and rendering function.

Parameters

  • {:directive_name, args} - The directive tuple with its arguments
  • context - The context map containing variables and data
  • opts - Options for rendering
  • render_fn - Function to recursively render templates (arity 3)

Supported Directives

  • #pipe - Thread data through a series of transformations (like Elixir's |> operator)
  • #map - Iterate over a collection and apply a template to each item
  • #flat_map - Map over a collection and flatten the results into a single list
  • #merge - Merge multiple maps together
  • #if - Conditional rendering based on a boolean condition
  • #case - Pattern matching on values (like Elixir's case)
  • #cond - Condition-based branching (like Elixir's cond)
  • #filter - Filter items in a collection based on a condition
  • #pick - Extract specific keys from a map (similar to Map.pick)

Examples

iex> Mau.MapDirectives.apply_directive({:map, ["{{$items}}", %{name: "{{$self.name}}"}]}, %{}, [], fn template, _context, _opts -> template end)
[]

iex> Mau.MapDirectives.apply_directive({:merge, [%{a: 1}, %{b: 2}]}, %{}, [], fn template, _context, _opts -> template end)
%{a: 1, b: 2}

match_directive(map)

Checks if a map contains a directive and returns the directive type and arguments.

Examples

iex> Mau.MapDirectives.match_directive(%{"#map" => ["collection", "template"]})
{:map, ["collection", "template"]}

iex> Mau.MapDirectives.match_directive(%{"#merge" => [%{}, %{}]})
{:merge, [%{}, %{}]}

iex> Mau.MapDirectives.match_directive(%{"name" => "John"})
:none