Converts structs into data that can be passed to a template.
Date, Time, NaiveDateTime, DateTime and Decimal become Typst datetimes and
decimals, and MapSets, Ranges and Date.Ranges become arrays, without this
protocol. Other structs must implement it to be passed to a template, so that their
internal fields (an Ecto schema's metadata, or a password hash) don't reach templates by
accident.
Derive it to pass a struct as a dictionary of its fields, or of some of them:
defmodule MyApp.Customer do
@derive {Typsty.Encoder, only: [:name, :email]}
defstruct [:name, :email, :password_hash]
end@derive Typsty.Encoder passes every field, and except: [...] leaves some out. An Ecto
schema's __meta__ field is always left out, and associations must be preloaded or left
out. Fields in :only and :except that the struct doesn't have raise when it compiles.
For structs from other libraries, derive it with Protocol.derive/3:
require Protocol
Protocol.derive(Typsty.Encoder, SomeLibrary.Struct, only: [:name])Or implement it, to pass a struct differently, such as a money struct as a formatted string:
defimpl Typsty.Encoder, for: MyApp.Money do
def encode(money), do: MyApp.Money.to_string(money)
endencode/1 can return any data a template accepts: maps, lists, strings, numbers,
booleans, nil, dates and decimals, or another struct.
Summary
Functions
Converts the struct into data for a template.
Types
@type t() :: term()
All the types that implement this protocol.