Open source · MITOpen source · MIT

Fill Word, Excel and PowerPoint templates from your data Заполняйте шаблоны Word, Excel и PowerPoint данными

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 — получите готовый документ. Циклы, условия, фильтры и картинки — всё бесплатно, без платных модулей.

JS npm install coffee-templater
Go go get github.com/vitJR1/coffee-templater.go

What it is forДля чего это

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 — то, что их соединяет.

W

Contracts & invoicesДоговоры и счета

Word templates with tables of line items, optional clauses, signatures and logos.Шаблоны Word с таблицами позиций, необязательными пунктами, подписями и логотипами.

X

Reports & exportsОтчёты и выгрузки

Excel sheets where rows repeat, numbers stay numbers and formulas like SUM stretch automatically.Листы Excel, где строки повторяются, числа остаются числами, а формулы вроде SUM растягиваются сами.

P

PresentationsПрезентации

PowerPoint decks with bullet lists, tables, speaker notes and pictures placed exactly in their boxes.Слайды PowerPoint со списками, таблицами, заметками и картинками ровно в своих рамках.

{ }

Reading documentsЧтение документов

Parse uploaded files into plain JSON: import Excel rows as objects, edit Word text, extract text for search.Разбор загруженных файлов в JSON: строки Excel как объекты, правка текста Word, извлечение текста для поиска.

FeaturesВозможности

Loops that know what to repeatЦиклы понимают, что повторять

Text inside a paragraph, whole paragraphs, table rows or sheet rows — decided by where you put the tags.Текст внутри абзаца, целые абзацы, строки таблицы или листа — по тому, где стоят теги.

Conditions & filtersУсловия и фильтры

{{#if}}…{{else}}, ~40 built-in filters (numbers, currency, dates, sorting) and your own in plain JS or Go.{{#if}}…{{else}}, около 40 встроенных фильтров (числа, валюты, даты, сортировка) и свои на обычном JS или Go.

Your syntaxСвой синтаксис

Any delimiters — {{x}}, ${x}, [[x]], <<x>> — and \{{escaping}} for literal text.Любые разделители — {{x}}, ${x}, [[x]], <<x>> — и \{{экранирование}} для буквального текста.

Survives WordНе боится Word

Word splits text into fragments while you type. Tags broken across them are glued back automatically.Word режет текст на фрагменты при наборе. Разорванные теги склеиваются автоматически.

ImagesКартинки

PNG, JPEG, GIF, SVG with auto-detected size — inline in Word, fitted into text boxes in PowerPoint.PNG, JPEG, GIF, SVG с автоопределением размера — в строку в Word и в рамку в PowerPoint.

Know your templateЗнайте свой шаблон

inspect() lists every variable and returns a sample data shape — build forms or validate input.inspect() перечисляет переменные и возвращает пример данных — для форм и проверки входа.

Documents as JSONДокумент как JSON

parse() → edit → build(), keeping all formatting the model doesn't touch.parse() → правка → build() с сохранением всего форматирования.

Safe for uploadsБезопасно для загрузок

Limits against zip bombs, deep XML and runaway loops; values are always escaped.Лимиты против zip-бомб, глубокого XML и бесконечных циклов; значения всегда экранируются.

Runs everywhereРаботает везде

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. Нигде никаких нативных зависимостей.

Template syntaxСинтаксис шаблонов

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}}

Excel that stays ExcelExcel остаётся Excel

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).

Try it right hereПопробуйте прямо здесь

This demo runs the real library in your browser. Files never leave your computer. Демо запускает настоящую библиотеку в вашем браузере. Файлы никуда не отправляются.

1

Choose a templateВыберите шаблон

DelimitersРазделители
2

Data (JSON)Данные (JSON)

3

RenderСгенерировать

Quick startБыстрый старт

Render a templateЗаполнить шаблон

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,
}))

Read an uploaded Excel fileПрочитать загруженный Excel

import { parseXlsxFile, sheetToObjects } from 'coffee-templater'

const book = parseXlsxFile(upload)
const rows = sheetToObjects(book.sheets[0])
// [{ Name: 'Tea', Qty: 2, Date: '2024-05-17' }, …]

Your own filters and syntaxСвои фильтры и синтаксис

createTemplater({
  delimiters: ['${', '}'],
  timeZone: 'Europe/Moscow',
  filters: { money: (v, cur) => `${v.toFixed(2)} ${cur}` },
})
// ${ total | money: "RUB" }

README · Full guide (Russian)Полное руководство · npm

One engine, many languagesОдно ядро — много языков

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.

JavaScript / TypeScript coffee-templater · npm Go coffee-templater.go · wazero
Python plannedв планах
coffee-templater-engine Rust → WebAssembly · templates, document model, ZIP/XML, safety limitsшаблоны, модель документа, ZIP/XML, лимиты