DocxTmpl

Make new .docx files from a Handlebars-like template.

Write a Word document with {{placeholders}}, {{#if}}, {{#unless}}, and {{#each}} blocks — then render it with a map of assigns to produce a fresh .docx. Word frequently splits a single placeholder across multiple <w:r> runs (fonts, spellcheck markers, tracked changes); DocxTmpl heals those before substitution so your templates Just Work.

Installation

Add docx_tmpl to your dependencies in mix.exs:

def deps do
  [
    {:docx_tmpl, "~> 0.2.0"}
  ]
end

Docs: https://hexdocs.pm/docx_tmpl.

Usage

{:ok, bytes} = DocxTmpl.render_file("invoice.docx", %{
  "customer" => "Acme Corp",
  "items" => [
    %{"name" => "Widget", "qty" => 3},
    %{"name" => "Gadget", "qty" => 1}
  ],
  "paid" => true
})

File.write!("invoice-acme.docx", bytes)

Template syntax inside the .docx:

Hello {{customer}}!

{{#each items}}
  - {{name}} × {{qty}}
{{/each}}

{{#if paid}}Thanks for your payment.{{/if}}
{{#unless paid}}Please remit within 30 days.{{/unless}}

{{#each}} wrapping a single <w:tr> repeats the table row.

{{image var}} standalone in a paragraph embeds an image. Pass it as %{bytes: <<...>>, format: :png, width_cm: 5, height_cm: 3} in assigns.

Inspect a template's variables without rendering:

{:ok, names} = DocxTmpl.variables(File.read!("invoice.docx"))
# => ["customer", "items", "name", "paid", "qty"]

Author

Ostap Brehin — https://github.com/osbre/docx_tmpl

License

MIT