# `Typsty.Encoder`
[🔗](https://github.com/akoutmos/typsty/blob/0.1.0/lib/typsty/encoder.ex#L1)

Converts structs into data that can be passed to a template.

`Date`, `Time`, `NaiveDateTime`, `DateTime` and `Decimal` become Typst datetimes and
decimals, and `MapSet`s, `Range`s and `Date.Range`s 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:

```elixir
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`:

```elixir
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:

```elixir
defimpl Typsty.Encoder, for: MyApp.Money do
  def encode(money), do: MyApp.Money.to_string(money)
end
```

`encode/1` can return any data a template accepts: maps, lists, strings, numbers,
booleans, `nil`, dates and decimals, or another struct.

# `t`

```elixir
@type t() :: term()
```

All the types that implement this protocol.

# `encode`

```elixir
@spec encode(t()) :: term()
```

Converts the struct into data for a template.

---

*Consult [api-reference.md](api-reference.md) for complete listing*
