#[derive(ToDict)]
{
// Attributes available to this derive:
#[typst]
}
Available on crate feature
derive only.Expand description
Derives ToDict (and, through it, ToValue) for a named
struct. See the derive crate for the full list
of #[typst(...)] attributes.
use typst_template::{ToDict, ToValue, Value};
fn cents(amount: i64) -> Value {
Value::Str(format!("{}.{:02}", amount / 100, amount % 100).into())
}
#[derive(ToDict)]
struct Meta {
locale: String,
}
#[derive(ToDict)]
#[typst(rename_all = "camelCase")]
struct Invoice {
client_name: String,
#[typst(rename = "amount", with = "cents")]
amount_cents: i64,
#[typst(skip)]
internal_id: u64,
#[typst(flatten)]
meta: Meta,
}
let dict = Invoice {
client_name: "ACME".into(),
amount_cents: 1050,
internal_id: 7,
meta: Meta { locale: "hr".into() },
}
.into_dict();
assert_eq!(dict.get("clientName").unwrap(), &Value::Str("ACME".into()));
assert_eq!(dict.get("amount").unwrap(), &Value::Str("10.50".into()));
assert_eq!(dict.get("locale").unwrap(), &Value::Str("hr".into())); // flattened
assert!(dict.get("internalId").is_err()); // skippedDerives ToDict (and, through it, ToValue) for a named struct.
Each field is converted to a Typst value via ToValue and inserted under
its name. The generated into_value wraps the resulting dict in
Value::Dict, so derived types nest inside one another.
§Attributes
Container level (#[typst(...)] on the struct):
rename_all = "..."— rename every field with one of the ruleslowercase,UPPERCASE,PascalCase,camelCase,snake_case,SCREAMING_SNAKE_CASE,kebab-case,SCREAMING-KEBAB-CASE.
Field level (#[typst(...)] on a field):
rename = "name"— use a fixed key, overridingrename_all.skip— leave the field out of the dict.with = "path::to::fn"— call that function (named as a string, like serde) asfn(field) -> Valueto produce the value instead of using the field’sToValueimpl. Useful for types that do not implement the trait or that need a custom representation.flatten— merge the field’s own dict into this one instead of nesting it under a key. The field type must implementToDict;rename/withare ignored for it.