Template Inputs
Oicana supports two types of inputs. A JSON input takes structured data while binary data can be passed into templates through a blob input.
Inputs are defined in the template manifest. Integrations can list all inputs of a template to, for example, validate input values or offer an editor.
JSON inputs
Section titled “JSON inputs”The type property of the input definition must be json. The only other required property is key.
[[tool.oicana.inputs]]type = "json"key = "data"development = "development-data.json"The following code snippet shows how to set the value for this input from your integration:
import { initialize, Template } from '@oicana/browser';
await initialize();
const response = await fetch('/template.zip');const templateBytes = new Uint8Array(await response.arrayBuffer());const template = new Template(templateBytes);
const jsonInputs = new Map<string, string>();jsonInputs.set('data', JSON.stringify({ name: 'Alice' }));
const pdf = template.export(jsonInputs, new Map());using System.Text.Json.Nodes;using Oicana;using Oicana.Config;using Oicana.Inputs;
var templateBytes = File.ReadAllBytes("template.zip");var template = new Template(templateBytes);
var jsonInputs = new Dictionary<string, JsonNode>{ ["data"] = JsonNode.Parse("""{ "name": "Alice" }""")!,};
var pdf = template.ExportPdf(jsonInputs);import 'dart:io';
import 'package:oicana/oicana.dart';
final template = await Template.load(File('template.zip').readAsBytesSync());try { final pdf = await template.exportPdf( jsonInputs: { 'data': {'name': 'Alice'}, }, );} finally { template.dispose();}Dart accepts Maps, Lists, and any other value jsonEncode accepts, or a String that already holds JSON. To pass a JSON string value, encode it first, for example jsonEncode('Alice').
templateBytes, err := os.ReadFile("template.zip")if err != nil { return err}template, err := oicana.NewTemplate(templateBytes)if err != nil { return err}defer template.Close()
pdf, err := template.ExportPdf(oicana.Inputs{ JSON: map[string]any{"data": map[string]any{"name": "Alice"}},})Go encodes each JSON input value with json.Marshal, so a struct works as well. A Go string becomes a JSON string; pass a json.RawMessage for JSON you already have.
import com.oicana.CompilationMode;import com.oicana.ExportFormat;import com.oicana.Template;import java.nio.file.Files;import java.nio.file.Path;import java.util.Map;
byte[] templateBytes = Files.readAllBytes(Path.of("template.zip"));try (var template = new Template(templateBytes)) { String json = "{\"name\":\"Alice\"}";
byte[] pdf = template.export( Map.of("data", json), Map.of(), ExportFormat.pdf(), CompilationMode.PRODUCTION);}import { readFile } from 'node:fs/promises';import { Template, Pdf } from '@oicana/node';
const templateBytes = await readFile('template.zip');const template = new Template(templateBytes);
const jsonInputs = new Map<string, string>();jsonInputs.set('data', JSON.stringify({ name: 'Alice' }));
const pdf = template.export(jsonInputs, new Map(), Pdf);use Oicana\CompilationMode;use Oicana\Template;
$templateBytes = file_get_contents('template.zip');$template = new Template($templateBytes);
try { $pdf = $template->export( jsonInputs: ['data' => ['name' => 'Alice']], mode: CompilationMode::Production, );} finally { $template->close();}PHP accepts either an associative array (as shown) or a pre-encoded JSON string for each JSON input.
import jsonfrom pathlib import Path
from oicana import CompilationMode, Template
template_bytes = Path("template.zip").read_bytes()
with Template(template_bytes) as template: pdf = template.export_pdf( json_inputs={"data": json.dumps({"name": "Alice"})}, mode=CompilationMode.PRODUCTION, )require "oicana"
Oicana::Template.open(File.binread("template.zip")) do |template| pdf = template.export_pdf(json_inputs: { "data" => { name: "Alice" } })endRuby accepts a Hash or any other value JSON.generate encodes, or a String that already holds JSON. To pass a JSON string value, encode it first, for example "Alice".to_json.
use std::fs::File;
use oicana::Template;use oicana::input::{CompilationConfig, JsonInput, TemplateInputs};
let template_file = File::open("template.zip")?;let mut template = Template::init(template_file)?;
let mut inputs = TemplateInputs::new();inputs.with_config(CompilationConfig::production());inputs.with_input(JsonInput::new( "data", serde_json::json!({ "name": "Alice" }).to_string(),));
let result = template.compile(inputs)?;Blob inputs
Section titled “Blob inputs”Blob inputs can be used for binary data like images. Additional metadata can be used to further specify the type of binary data in the input.
[[tool.oicana.inputs]]type = "blob"key = "logo"development = { file = "development-logo.png" }As a common use case for blob inputs, images have special support in the oicana Typst package.
To set the value for this input from your integration, pick your language. Each example reads a logo.png file and passes its bytes along with an image_format metadata entry so the oicana-image helper can pick the right decoder:
import { initialize, Template, type BlobInput } from '@oicana/browser';
await initialize();
const templateResponse = await fetch('/template.zip');const templateBytes = new Uint8Array(await templateResponse.arrayBuffer());const template = new Template(templateBytes);
const logoResponse = await fetch('/logo.png');const logo = new Uint8Array(await logoResponse.arrayBuffer());
const blobInputs = new Map<string, BlobInput>();blobInputs.set('logo', { data: logo, metadata: { image_format: 'png' },});
const pdf = template.export(new Map(), blobInputs);using System.Text.Json.Nodes;using Oicana;using Oicana.Config;using Oicana.Inputs;
var templateBytes = File.ReadAllBytes("template.zip");var template = new Template(templateBytes);
var logo = File.ReadAllBytes("logo.png");
var blobInputs = new Dictionary<string, BlobInput>{ ["logo"] = new BlobInput(logo, new BlobMeta { ImageFormat = "png" }),};
var pdf = template.ExportPdf(blobInputs: blobInputs);import 'dart:io';
import 'package:oicana/oicana.dart';
final template = await Template.load(File('template.zip').readAsBytesSync());try { final logo = File('logo.png').readAsBytesSync();
final pdf = await template.exportPdf( blobInputs: { 'logo': BlobInput(logo, metadata: {'image_format': 'png'}), }, );} finally { template.dispose();}templateBytes, err := os.ReadFile("template.zip")if err != nil { return err}template, err := oicana.NewTemplate(templateBytes)if err != nil { return err}defer template.Close()
logo, err := os.ReadFile("logo.png")if err != nil { return err}
pdf, err := template.ExportPdf(oicana.Inputs{ Blobs: map[string]oicana.Blob{ "logo": {Data: logo, Metadata: map[string]any{"image_format": "png"}}, },})import com.oicana.BlobInput;import com.oicana.CompilationMode;import com.oicana.ExportFormat;import com.oicana.Template;import java.nio.file.Files;import java.nio.file.Path;import java.util.Map;
byte[] templateBytes = Files.readAllBytes(Path.of("template.zip"));try (var template = new Template(templateBytes)) { byte[] logo = Files.readAllBytes(Path.of("logo.png"));
byte[] pdf = template.export( Map.of(), Map.of("logo", new BlobInput(logo, Map.of("image_format", "png"))), ExportFormat.pdf(), CompilationMode.PRODUCTION);}import { readFile } from 'node:fs/promises';import { Template, Pdf, type BlobInput } from '@oicana/node';
const templateBytes = await readFile('template.zip');const template = new Template(templateBytes);
const logo = await readFile('logo.png');
const blobInputs = new Map<string, BlobInput>();blobInputs.set('logo', { data: logo, metadata: { image_format: 'png' },});
const pdf = template.export(new Map(), blobInputs, Pdf);use Oicana\CompilationMode;use Oicana\Inputs\BlobInput;use Oicana\Template;
$templateBytes = file_get_contents('template.zip');$template = new Template($templateBytes);
try { $logo = file_get_contents('logo.png');
$pdf = $template->export( blobInputs: [ 'logo' => new BlobInput($logo, ['image_format' => 'png']), ], mode: CompilationMode::Production, );} finally { $template->close();}from pathlib import Path
from oicana import BlobInput, CompilationMode, Template
template_bytes = Path("template.zip").read_bytes()
with Template(template_bytes) as template: logo = Path("logo.png").read_bytes()
pdf = template.export_pdf( blob_inputs={ "logo": BlobInput(data=logo, metadata={"image_format": "png"}), }, mode=CompilationMode.PRODUCTION, )require "oicana"
Oicana::Template.open(File.binread("template.zip")) do |template| logo = File.binread("logo.png")
pdf = template.export_pdf( blob_inputs: { "logo" => Oicana::BlobInput.new(data: logo, metadata: { image_format: "png" }) }, )enduse std::fs::File;
use oicana::Template;use oicana::input::{BlobInput, CompilationConfig, ImageFormat, TemplateInputs};
let template_file = File::open("template.zip")?;let mut template = Template::init(template_file)?;
let logo = std::fs::read("logo.png")?;
let mut inputs = TemplateInputs::new();inputs.with_config(CompilationConfig::production());inputs.with_input(BlobInput::image("logo", logo, ImageFormat::Png));
let result = template.compile(inputs)?;Metadata is optional in every integration. PNG and JPEG are recognized from their byte signature, so oicana-image picks the right decoder even without an image_format entry. Set it when you want to be explicit.
Default and Development values
Section titled “Default and Development values”Inputs can define two different fallback values, default and development.
When compiling a template in development mode, input values have the priority
- Explicit input value
developmentvaluedefaultvalue
If you compile in production mode, the development value is ignored:
- Explicit input value
defaultvalue
While developing an Oicana template in a Typst editor, it will be compiled in development mode. It makes sense to define development values for all required inputs of your template to have a functioning preview.
Considering a template with the files development-data.json, default-data.json, development-logo.png, and default-logo.png. It could define the following inputs:
[[tool.oicana.inputs]]type = "json"key = "data"development = "development-data.json"default = "default-data.json"
[[tool.oicana.inputs]]type = "blob"key = "logo"development = { file = "development-logo.png", meta = { image_format = "png", foo = 5, bar = ["development", "two"] } }default = { file = "default-logo.png", meta = { image_format = "png", foo = 5, bar = ["default", "two"] } }The default.meta objects for blob fallback values are optional.
In the preview of an editor, the content of development-data.json and development-logo.png would be used. If compiled in production mode through an Oicana integration, the default fallbacks would be used if the input values are not set programmatically.
Required inputs
Section titled “Required inputs”By default, all inputs are required. If a required input has no value after resolving fallbacks (considering the compilation mode), Oicana will produce a compile error.
You can mark an input as optional by setting required = false:
[[tool.oicana.inputs]]type = "json"key = "extra-data"required = falseOptional inputs without a value will have a none value in the input dictionary returned by the setup function.
Every integration except Rust compiles a template once in development mode when you register it, to warm up the cache. A required input with neither a development nor a default value makes that warm-up fail, so creating the template throws. Either give the input a fallback value, or pass inputs for the warm-up to the template constructor (or Template.create in Node.js). All constructors take JSON inputs, blob inputs, and the warm-up mode as optional arguments after the template bytes.
This is useful for inputs that templates can handle gracefully when absent, while still getting a clear error for inputs that must always be provided.
Undeclared inputs
Section titled “Undeclared inputs”Every input value you pass has to match an input definition in the manifest. Oicana rejects a compilation if
- the template declares no input with a given key,
- the value is of the wrong kind, for example a JSON value for an input declared as
blob, - the same key is passed both as a JSON and as a blob input.
JSON schemas
Section titled “JSON schemas”A JSON input can point at a JSON Schema with the schema property. The schema is what oicana validate checks fallback values against, what oicana test fuzzes from, and what rejects bad input values before a compilation starts.
[[tool.oicana.inputs]]type = "json"key = "data"schema = "schemas/data.schema.json"- The path is relative to the template root, the same as every other file reference in the manifest, and it may point into a subdirectory.
- The schema file is read out of the packed template, so it has to be packed with it. Do not exclude it.
- The dialect is taken from the schema’s
$schemakeyword. Drafts 4, 6, 7, 2019-09, and 2020-12 are supported; without$schema, the newest one is assumed. - References within the same file (
#/$defs/...,#/definitions/...) work. References to other files do not.
Schemas are compiled when the template is registered. A value that violates the schema fails before Typst runs, with the offending paths listed:
error: Input 'data' failed schema validation: - At /person/name: "A" is shorter than 2 charactersValidation configuration
Section titled “Validation configuration”By default, all explicit JSON input values with a schema are validated before compilation. You can control this on two levels.
Per-template default
Section titled “Per-template default”The validate_json_inputs_by_default property in [tool.oicana] controls whether validation for JSON inputs with schemas is enabled. It defaults to true. Setting it to false means the template starts with validation disabled, though integrations can still toggle it at runtime per template instance.
[tool.oicana]manifest_version = 1validate_json_inputs_by_default = falsePer-input
Section titled “Per-input”Each JSON input has an optional validate property that defaults to true. Setting it to false prevents Oicana from compiling a schema validator for that input, even if a schema is defined. This is useful when a schema is only needed for test fuzzing and not for runtime validation.
[[tool.oicana.inputs]]type = "json"key = "data"schema = "data.schema.json"validate = falseNote that validate = false on an input is different from validate_json_inputs_by_default = false on the template. The per-input flag prevents validation entirely, while the template-level flag still allows integrations to change the validation behavior at runtime.
Using inputs in Typst
Section titled “Using inputs in Typst”To access input values in your template, use the setup function from the oicana Typst package:
#import "@preview/oicana:0.2.1": setup
#let read-project-file(path) = read(path, encoding: none)#let (input, oicana-image, oicana-config) = setup(read-project-file)inputis a dictionary of resolved input values, keyed by the input’skeyoicana-imageis a helper function that takes a blob input key and returns a Typst image elementoicana-configcontains compilation metadata likeproduction: true/false
For blob inputs that are images, you can use the oicana-image helper instead of accessing the raw bytes:
#oicana-image("logo", alt: "Company logo")If you don’t want to use the helper method, you can use the blob input as a dictionary with the raw bytes and its metadata in meta. Since metadata is optional, read entries with a default:
#let logo = input.logo#image(logo.bytes, format: logo.meta.at("image_format", default: auto), alt: "Company logo")For JSON inputs, access the parsed data directly:
#let name = input.invoice.buyer.name