Contracts & invoicesДоговоры и счета
Word templates with tables of line items, optional clauses, signatures and logos.Шаблоны Word с таблицами позиций, необязательными пунктами, подписями и логотипами.
Open source · MITOpen source · MIT
Put {{tags}} into a regular .docx, .xlsx or .pptx, pass JSON — get a finished document. Loops, conditions, filters and images included. Everything is free: no paid modules.
Расставьте {{теги}} в обычном .docx, .xlsx или .pptx, передайте JSON — получите готовый документ. Циклы, условия, фильтры и картинки — всё бесплатно, без платных модулей.
npm install coffee-templater
go get github.com/vitJR1/coffee-templater.go
Backends generate documents all the time: invoices, contracts, acts, reports, exports. Non-developers design the layout in Office; your code fills in the data. coffee-templater is the piece in between. Бэкенды постоянно генерируют документы: счета, договоры, акты, отчёты, выгрузки. Макет делают в Office люди без программирования, а код подставляет данные. coffee-templater — то, что их соединяет.
Word templates with tables of line items, optional clauses, signatures and logos.Шаблоны Word с таблицами позиций, необязательными пунктами, подписями и логотипами.
Excel sheets where rows repeat, numbers stay numbers and formulas like SUM stretch automatically.Листы Excel, где строки повторяются, числа остаются числами, а формулы вроде SUM растягиваются сами.
PowerPoint decks with bullet lists, tables, speaker notes and pictures placed exactly in their boxes.Слайды PowerPoint со списками, таблицами, заметками и картинками ровно в своих рамках.
Parse uploaded files into plain JSON: import Excel rows as objects, edit Word text, extract text for search.Разбор загруженных файлов в JSON: строки Excel как объекты, правка текста Word, извлечение текста для поиска.
Text inside a paragraph, whole paragraphs, table rows or sheet rows — decided by where you put the tags.Текст внутри абзаца, целые абзацы, строки таблицы или листа — по тому, где стоят теги.
{{#if}}…{{else}}, ~40 built-in filters (numbers, currency, dates, sorting) and your own in plain JS or Go.{{#if}}…{{else}}, около 40 встроенных фильтров (числа, валюты, даты, сортировка) и свои на обычном JS или Go.
Any delimiters — {{x}}, ${x}, [[x]], <<x>> — and \{{escaping}} for literal text.Любые разделители — {{x}}, ${x}, [[x]], <<x>> — и \{{экранирование}} для буквального текста.
Word splits text into fragments while you type. Tags broken across them are glued back automatically.Word режет текст на фрагменты при наборе. Разорванные теги склеиваются автоматически.
PNG, JPEG, GIF, SVG with auto-detected size — inline in Word, fitted into text boxes in PowerPoint.PNG, JPEG, GIF, SVG с автоопределением размера — в строку в Word и в рамку в PowerPoint.
inspect() lists every variable and returns a sample data shape — build forms or validate input.inspect() перечисляет переменные и возвращает пример данных — для форм и проверки входа.
parse() → edit → build(), keeping all formatting the model doesn't touch.parse() → правка → build() с сохранением всего форматирования.
Limits against zip bombs, deep XML and runaway loops; values are always escaped.Лимиты против zip-бомб, глубокого XML и бесконечных циклов; значения всегда экранируются.
Node.js 18+ and browsers with TypeScript types; Go 1.23+ without cgo. No native dependencies anywhere.Node.js 18+ и браузеры с типами TypeScript; Go 1.23+ без cgo. Нигде никаких нативных зависимостей.
Small and Mustache-like. Type it right into Word, Excel or PowerPoint. Небольшой, в духе Mustache. Пишется прямо в Word, Excel или PowerPoint.
{{client.name}} | variableпеременная |
{{price | number: 2}} | filterфильтр |
{{#items}}…{{/items}} | loopцикл |
{{#if paid}}…{{else}}…{{/if}} | conditionусловие |
{{@number}}, {{../title}} | loop index, parent scopeномер в цикле, внешняя область |
{{%logo}} | imageкартинка |
\{{text}} | literal {{text}}буквально {{text}} |
With 100 rows of data, row 3 becomes rows 3–102, every =B3*C3 points to its own row, and the total becomes =SUM(D3:D102).
Со 100 строками данных строка 3 превратится в строки 3–102, каждая =B3*C3 будет ссылаться на свою строку, а итог станет =SUM(D3:D102).
This demo runs the real library in your browser. Files never leave your computer. Демо запускает настоящую библиотеку в вашем браузере. Файлы никуда не отправляются.
import { readFileSync, writeFileSync } from 'node:fs'
import { createTemplater } from 'coffee-templater'
const templater = createTemplater()
const template = templater.compile(readFileSync('invoice.docx'))
writeFileSync('invoice-42.docx', template.render({
number: 42,
client: { name: 'Ivan Petrov' },
items: [{ name: 'Coffee', qty: 2, price: 10.5 }],
paid: false,
}))
import { parseXlsxFile, sheetToObjects } from 'coffee-templater'
const book = parseXlsxFile(upload)
const rows = sheetToObjects(book.sheets[0])
// [{ Name: 'Tea', Qty: 2, Date: '2024-05-17' }, …]
createTemplater({
delimiters: ['${', '}'],
timeZone: 'Europe/Moscow',
filters: { money: (v, cur) => `${v.toFixed(2)} ${cur}` },
})
// ${ total | money: "RUB" }
import coffee "github.com/vitJR1/coffee-templater.go"
templater := coffee.New(coffee.Options{})
template, _ := os.ReadFile("invoice.docx")
doc, err := templater.Render(ctx, template, map[string]any{
"number": 42,
"client": map[string]any{"name": "Ivan Petrov"},
"items": []map[string]any{
{"name": "Coffee", "qty": 2, "price": 10.5},
},
"paid": false,
})
os.WriteFile("invoice-42.docx", doc, 0o644)
book, err := coffee.Parse(ctx, upload)
rows := coffee.SheetToObjects(book.Sheets[0], 1)
// [map[Name:Tea Qty:2 Date:2024-05-17] …]
coffee.New(coffee.Options{
Delimiters: coffee.Delimiters{Start: "${", End: "}"},
TimeZone: moscow,
Filters: map[string]coffee.Filter{
"money": func(v any, args ...any) (any, error) {
return fmt.Sprintf("%.2f %v", v, args[0]), nil
},
},
})
// ${ total | money: "RUB" }
README · Full guide (Russian)Полное руководство · npm
README · Full guide (Russian)Полное руководство · pkg.go.dev
All document work happens in coffee-templater-engine — a Rust core compiled to WebAssembly and embedded in every library. JavaScript and Go run the very same engine, so a template renders byte-for-byte the same in Node.js, the browser and Go. Python is next. Вся работа с документами выполняется в coffee-templater-engine — ядре на Rust, скомпилированном в WebAssembly и встроенном в каждую библиотеку. JavaScript и Go работают на одном и том же ядре, поэтому шаблон даёт побайтно одинаковый результат в Node.js, браузере и Go. Следующий — Python.