Export templates API reference
Section titled “Export templates API reference”This page is for integrators and developers who export records with a template through the API, read or write template definitions, or need to know exactly how a template is rendered.
Two template concepts
Section titled “Two template concepts”OSOS has two distinct template concepts, both stored inside the
DataEntity document (not as standalone collections):
- Export templates — uploaded Word/HTML/Excel files that OSOS fills with
entry data to produce DOCX, PDF, or XLSX documents. These drive the
entries/export/{templateId}endpoint. - Display templates and template parameters — a
templateIdplus a set of parameterized bindings (TemplateParameter) attached to an entity or a view, used to parameterize how an entry or list is rendered.
The supported outputs are DOCX, HTML, and XLSX, with DOCX/HTML → PDF
conversion. Template exports never produce CSV: CSV is offered only by the two quick
exports of a gallery or of an entity’s entries (format=xlsx|csv, Since 1.10; see
Quick export of an entity’s entries).
Template values are filled with tokens/expressions resolved against the entry at
export time, and JavaScript plus custom functions can be used inside the template.
Reports are not rendered by this engine. An earlier version of the builder page
listed Reports among the places templates are used, “rendering through the same
engine”. In the code, a report renders through ReportService → ExportService
(data-service/src/services/report.service.ts), not through
DataEntryTemplateExportService; see Reports.
Sensitive fields in a template export Since 1.10
Section titled “Sensitive fields in a template export Since 1.10”A template carries its own sensitiveDataAccessPolicy (Prohibited, Privileged,
User-Based, Auto; absent = Privileged). The template read disables the
caller-scoped mask (disabledStages.hideSensitiveFields: true) and, when the
template’s policy resolves to anything short of a full reveal, passes
elementSensitiveAccess with the resolved grant scopes instead. The template’s own
policy applies even when a reaction’s Generate File action renders it (a
reaction’s policy does not override it). An unknown executor makes a User-Based or
Auto template mask (fail closed). Encrypted fields are masked unconditionally by
maskFieldsExcludedFromBuilders before any expression is evaluated or anything is
rendered. See Sensitive-data access policy.
Template file syntax
Section titled “Template file syntax”The authoring syntax for HTML (EJS), Word and Excel templates, with examples, is in Export templates — Write the template file.
Concepts and data model
Section titled “Concepts and data model”Export template (DataEntityExportTemplate)
Section titled “Export template (DataEntityExportTemplate)”Export templates are stored on DataEntity.templates (IDataEntityExportTemplate[]). Each template references an uploaded source file and declares how it should be rendered and delivered.
| Field | Type | Required | Meaning |
|---|---|---|---|
id | UUID | yes | Template identifier (used as templateId in the export endpoint) |
name | LocalizedValue | yes | Localized template name; also the default output file name |
level | TemplateLevelEnum | yes | SingleEntry (0) or MultipleEntries (1) |
type | TemplateTypeEnum | yes | Output format: Word (0), PDF (1), Excel (2) |
file | FileModel | yes | The uploaded source template file (has id, mimeType, name) |
exportType | TemplateExportTypeEnum | yes | UI (0) = synchronous download, Background (1) = async via service bus |
additionalProperties | Record<string,string> | no | Custom variables (expressions) and feature flags such as extended |
query | reference or null | no | Since 1.10. Saved query an entry must meet (Single Entry only) — see Conditional export |
criteria | FilterExpression | no | Since 1.10. Filter an entry must meet (Single Entry only) |
nonMatchEntriesMode | enum | no | Since 1.10. Disable (0, default) or Hidden (1) for entries that do not meet the condition |
sensitiveDataAccessPolicy | SensitiveDataAccessPolicyEnum | no | Since 1.10. What the template may disclose from sensitive fields; absent = Privileged. See Sensitive fields in a template export |
Notes verified from code:
type(the requested output format) is independent of the source file’s MIME type. Fortype === PDF, the service branches onfile.mimeType: a DOCX source is rendered then converted DOCX→PDF; an HTML source is rendered then converted HTML→PDF. Any other source MIME type for a PDF template yields no file.levelcontrols per-entry helpers:getEntryCommentsandgetEntryEmailsreturn[]unlesslevel === SingleEntry(see Custom functions).
Template engines by type
Section titled “Template engines by type”The output format determines which templating engine runs:
type | Source file | Engine | Delimiters |
|---|---|---|---|
Word | DOCX | docx-templates createReport | {{ … }} (cmdDelimiter), fixSmartQuotes: true |
PDF (from DOCX) | DOCX | docx-templates, then DOCX→PDF conversion | {{ … }} |
PDF (from HTML) | HTML | ejs.render (async), then HTML→PDF conversion | openDelimiter: '{{', closeDelimiter: '}}' |
Excel | XLSX | xlsx-template (substitute(1, data)); a streamable template is written by ExcelJS’s streaming writer instead (Since 1.4, see Large exports) | library default (${...} placeholders) |
The data object passed to every engine is { entries, entity } (plus extra collections for extended export — see below). For Excel, entries are first flattened by mapEntriesForExcelTemplate: resolved reference arrays are collapsed to comma-joined mainTitle strings per available language, and vertical-tab characters are replaced with spaces.
Template parameters (TemplateParameter)
Section titled “Template parameters (TemplateParameter)”Since 1.4.
Display/parameterized templates use TemplateParameter, defined in models/template-parameter.model.ts and @osos/shared.
| Field | Type | Required | Meaning |
|---|---|---|---|
name | string | yes | Parameter name; must match the parameter name in the template |
valueType | TemplateParameterValueTypeEnum | yes | Fixed (0), Expression (1), Field (2) |
value | any | no | Fixed value, or an entry expression such as value.my_block[scope.index].my_field when Expression |
component | string | no | Optional component reference |
source | string | no | Optional source reference |
valueType semantics from the model JSDoc: Fixed — value is used verbatim; Expression — value is an entry expression evaluated to produce the value; Field — value type 2 (the enum member exists; its resolution is performed by consumers, see Notes and uncertainties).
Parameters are grouped by render context in TemplateParameterTypes:
interface TemplateParameterTypes { listEntry?: TemplateParameter[]; // list rendering viewEntry?: TemplateParameter[]; // read/view rendering editEntry?: TemplateParameter[]; // edit rendering}This bundle is attached in two places, both { templateId, parameters }:
DataEntity.displayTemplate→EntityDisplayTemplate- A data view →
ViewDisplayTemplate
API endpoints
Section titled “API endpoints”Export entries with a template
Section titled “Export entries with a template”GET /v1/entities/{entity}/entries/export/{templateId}Controller: DataEntryTemplateExportController.exportEntriesWithTemplateV2. Authenticated (Auth2 strategy). Produces a file download (application/vnd.openxmlformats-officedocument.spreadsheetml.sheet, ...wordprocessingml.document, or application/pdf) or a JSON acknowledgement.
Path parameters:
| Name | In | Meaning |
|---|---|---|
entity | path | Data entity id |
templateId | path | Export template id (the id on DataEntity.templates[*]) |
Query parameters:
| Name | Type | Meaning |
|---|---|---|
mode | number (ExportWithTemplateSourceMode) | SelectedItems (0) or source (1) |
itemsToExport | string[] | Entry ids to export; required when mode === SelectedItems |
filterCriteria | object | Filter criteria applied when mode === source |
search | string | Free-text search (ignored/forced undefined in SelectedItems mode) |
sourceCollection | string | Collection id; its items are added as an _id IN (...) filter in source mode |
appliedQuickFilters | string[] | Quick-filter ids |
Behavior (verified):
- Loads the entity, then
getEntityTemplate(dataEntity, templateId)— throwsTemplateNotExists(HTTP 404, codeTEMPLATE_NOT_EXIST) if no template with that id exists on the entity. - Extended templates — if
additionalProperties.extended === 'true', delegates toDataEntryExtendedTemplateExportService.exportFromTemplate(see Extended export). Always synchronous. - Background export — else if
exportType === Background, sends anExportTemplateInBackgroundCommandon the service bus and immediately returns200 { "success": true }. The file is generated asynchronously byExportTemplateInBackgroundHandlerand delivered via aFileGeneratedEvent. - UI export — else renders synchronously via
exportEntriesWithTemplate, uploads the result to storage, publishesFileGeneratedEvent, setsContent-Type/attachment headers, and streams the file body back.
In cases 2 and 4 the generated file is also uploaded to the storage service and a FileGeneratedEvent is published (carrying the file, template id, exportType, entity id, and the list of exported entry ids).
Error cases:
| Condition | Exception | HTTP |
|---|---|---|
No template with templateId on the entity | TemplateNotExists | 404 |
mode === SelectedItems with empty/missing itemsToExport | MustProvideITemsToExportProperty | 400 |
The entry does not meet the template’s condition, or a conditioned template is called in source mode (Since 1.10) | TEMPLATE_CONDITIONS_NOT_MET | 422 |
Check whether a template is in use
Section titled “Check whether a template is in use”GET /v1/templates/{id}/usedController: TemplatesController.isTemplateUsed. Returns a boolean. Long-standing.
This operates on templates stored as data entries in the internal templates entity (StringConstants.TEMPLATES_ENTITY_NAME = 'templates'), i.e. message/email templates referenced by entity triggers — not on the DataEntityExportTemplate export templates above.
Logic (verified):
- Look up the template entry by
id; returnfalseif it does not exist. - If the template’s
value.template_type.id === 'EMAIL_PART_TEMPLATE', find the main templates that reference this part as their header or footer (value.template_details.template_header.dataEntry/template_footer.dataEntryequal toid); collect those ids. Otherwise the candidate set is just this template’s own id. - Return
trueif anyDataEntityhas a trigger action wired to one of those template ids (triggers.actions.options.template IN (...)); otherwisefalse.
Rendering pipeline
Section titled “Rendering pipeline”exportEntriesWithTemplate is the core renderer used by the UI export path, the background handler, and the internal GenerateFileFromTemplateHandler. Steps:
- Fetch the source file from storage as an
arraybuffer. - Resolve the output file name — the passed
selectedFileName, else the localized templatename. - Gather export data (
getTemplateExportData):mode === source: builds filters from the source collection’sitems(_id IN) and anyfilterCriteria.criteria.mode === SelectedItems: requiresitemsToExport, forcessearch = undefined, and filters_id IN itemsToExport.- A view-triggered export reads through the view’s own columns. The view’s configured
fieldsare its display columns, andbuildScopeuses the same list both to narrow which relation/ADT fields it resolves and to build the read’s$project, so a template referencing a field the triggering view does not display renders that field blank (known limitation, still open). An earlier version of this page said the export widened to every non-sensitive fieldSince 1.8; that widening was reverted, because a$projectnaming both a block and its sub-field (value.addressandvalue.address.street) is a MongoDB path collision that produced a file with no records at all (data-entry-template-export.service.ts,getTemplateExportDataJSDoc). The view’s row-level scoping (obsolete/invalid/archived and search rules, its query data source, its default sorting) still applies. - Runs
dataEntryService.findWithResolvesFactorywithdisabledStages.hideSensitiveFields: true— this disables the caller-scoped mask, so the template’s own sensitive-data access policy decides (elementSensitiveAccess); Encrypted fields are then masked unconditionally. - If the template declares
additionalProperties, evaluates them per entry (see Custom variables).
- Render with the engine matching
type(see the table above), injecting the shared custom functions. - Return
{ fileName, fileContent, mimeType, exportEntriesIds }.
Custom variables
Section titled “Custom variables”Long-standing.
additionalProperties is a Record<string, string> where each value is an expression wrapped in {{%= … %}}. During data gathering, parseAdditionalProperties strips the {{%= / %}} wrappers, evaluates the inner expression per entry via executeExpression, and merges the results into each entry.value under the property key — making them available to the template as normal fields.
executeExpression builds a JS Function whose scope is { ...sharedCustomFunctions, entry, dataEntity }, evaluates return <expression>;, and awaits the result if it is a function call and/or Promise. Because expressions are evaluated as raw JavaScript, they run with full access to the shared function set below.
The reserved key extended (additionalProperties.extended === 'true') is a feature flag, not a variable — it routes the export to the extended service.
Custom functions in templates
Section titled “Custom functions in templates”Every render (docx, html/ejs, and expression evaluation) receives a shared function set from getSharedCustomFunctions(entity, templateConfig). Verified functions:
| Function | Purpose |
|---|---|
today(manipulateAmount?) | Current date, timezone-adjusted, with optional date-math manipulation |
date(value, formatString?, tzOffset?) | Format a date (default Constants.DATE_FORMAT), timezone-adjusted |
loc(localizedValue) | Resolve a LocalizedValue to the user’s language |
formula(text) | Excel only: the one way to emit a formula cell (a plain string starting with = stays text) |
mdToText(value) | Strip Markdown to plain text (also normalizes single-tilde strikethrough and line breaks) |
fetchEntry(ref) | Resolve a single referenced entry from { dataEntity, dataEntry } |
fetchEntriesById(entityId, entriesIds) | Resolve multiple entries by id |
fetchEntries(entityId, filter) | Resolve entries by an arbitrary filter |
getStepName(entry, stepId) | Workflow step name (falls back to ad-hoc steps) |
getCurrentStepOwner(entry) | Owner of the active current step (if it has a resolved mainTitle) |
getStepOwner(entry, stepId) | Owner of a step from workflow history |
getStepReceivedAt(entry, stepId?) | Received-at timestamp for a step (handles recievedAt/receivedAt) |
getStepActions(entry, stepId) | Actions defined on a step |
getStepActionName(entry, stepId, actionId) | Name of a specific step action |
getStepHistory(entry, stepId) | All history records for a step in the active workflow |
getStepLastHistory(entry, stepId) | Most recent history record for a step |
getEntryComments(entry, lang?) | Entry comments (with mentions resolved); [] unless level === SingleEntry |
getEntryEmails(entry) | Emails associated with the entry; [] unless level === SingleEntry |
DOCX and HTML renders additionally get:
- DOCX —
getImage(image, width, height, entryId?, alt?)returns image bytes for embedding (supported extensions:png,gif,jpg,jpeg,svg; unsupported extensions are logged and skipped) andmdToHtml(value)renders Markdown to HTML wrapped in<body>…</body>(with single- and double-tilde strikethrough support). - HTML/EJS —
getImageSrc(image, entryId?)returns a base64data:URI for the image, andmdToHtml(value)(configured withbreaks: true).
Background export
Section titled “Background export”When exportType === Background, the endpoint enqueues an ExportTemplateInBackgroundCommand (carrying the entity id, the full entityTemplate, mode, itemsToExport, sourceCollection, filterCriteria, search, view, and appliedQuickFilters) with sticky attributes for user, space, and delegation, then returns { success: true }.
ExportTemplateInBackgroundHandler re-loads the entity, calls the same exportEntriesWithTemplate, uploads the result, and publishes a FileGeneratedEvent (with exportType = Background) plus a CommandExecutedMessage over the socket. Errors are logged and swallowed (no failure event is published on error in this handler).
Internal: generate file from template
Section titled “Internal: generate file from template”GenerateFileFromTemplateHandler handles GenerateFileFromTemplateCommand (used by workflow/automation actions, not an HTTP route). It optionally loads a view by viewId, resolves the entity and template, calls exportEntriesWithTemplate with command.fileName, optionally uploads to storage when uploadToStorageService is set, and returns the file (or the uploaded file record) in a CommandExecutedMessage. On error it emits a CommandExecutedMessage with success: false and the error.
Extended export
Section titled “Extended export”Since 1.6.
DataEntryExtendedTemplateExportService.exportFromTemplate is used when additionalProperties.extended === 'true'. It runs the same gather-and-render pipeline but always in source mode and enriches the template data object with entity-model context beyond { entries, entity }:
{ entries, entity, module, reactions, notifications, workflows, lists, queries, views, relations }These are resolved from the data entity (getModule, getReactions, getNotifications, getWorkflows, getLists, getQueries, getViews, getRelations), making it suitable for generating documentation/specification exports of an entity’s configuration itself. It shares the same engine selection and custom-function set as the base service. This path is always synchronous (no background branch).
Streamed Excel exports Since 1.4
Section titled “Streamed Excel exports Since 1.4”An Excel template export of many entries is written page by page (500 entries at a time, each page written and released before the next is read) when the template has a simple enough shape; any other shape is rendered in memory as before. The difference matters at scale: in the measurement that came with the change, 25,000 entries took 12.8 s instead of 323 s, with about a quarter of the memory, and the file was 3 MB instead of 24 MB. This was also delivered to the 1.4, 1.6 and 1.8 lines as an update.
A template is streamed only when all of these hold:
- It has exactly one sheet.
- Every placeholder fills a whole cell, is a plain
${table:entries.<key>}(no sub-type), and all of them sit on the same row; that row holds nothing else. - Nothing below that row has a value, and no merged range reaches the table row or below it.
- The sheet has no formulas, images, Excel tables, conditional formatting, data validation, auto-filter or defined names.
When a template does not qualify, data-service logs the reason at INFO (template <id> of entity <id> is rendered in memory: it …), which tells you what to remove. Operators can force every template back to in-memory rendering with TEMPLATE_EXPORT_XLSX_STREAMING_DISABLED=true. On both paths a user value that starts with = stays text; only a value produced by the formula() expression helper is written as a formula.
Templates on virtual entities Since 1.6
Section titled “Templates on virtual entities Since 1.6”The Templates tab is also available on virtual entities such as Groups: templates can be managed on a virtual entity when it is not implicit, or when it is implicit but allows editing (implicitOptions.allowEdit); otherwise the entity’s normal edit rule applies. A template on a proxy, joiner or aggregate virtual entity is saved through the virtual-entity endpoint (PUT /v1/entities/virtual/{id}). A template export over a virtual entity includes the rows the user selected. Both were also delivered to the 1.6 and 1.8 lines as an update (the selected-rows fix also to the 1.4 line). For the other admin operations on virtual entities, see Virtual entities: admin operations.
Conditional export Since 1.10
Section titled “Conditional export Since 1.10”A Single Entry export template can carry a condition, so that only entries that meet it can be exported with that template. In the template form, the Filter section sets the condition and For other entries decides what users see on an entry that does not meet it: Disable export option (the default) or Hide export option. A Multiple Entries template cannot have a condition (its filter controls are disabled). A template without a condition behaves exactly as before.
The condition is stored on the template:
| Property | Meaning |
|---|---|
query | A saved query the entry must meet (null clears it). |
criteria | A filter expression the entry must meet. |
nonMatchEntriesMode | Disable (0, the default when absent) or Hidden (1) — the same values system buttons use. |
A template “has a condition” when it is Single Entry and has a saved query or at least one criteria rule; an empty rule group is not a condition. A saved query that cannot be loaded, or criteria that cannot be parsed, matches no entry (and is logged).
- Status route.
POST /v1/entities/{entity}/templates/status/entrieswith{dataEntriesIds: string[]}(1 to 100 ids) returns[{templateId, isDisabled, isHidden}]for each conditioned template. Through a view it reports only the templates that view exposes, and evaluates conditions only when the view can read every requested entry; outside a view it is open to system viewers and above, like the export route. Row and entry-details menus use it to show each template enabled, disabled (with the reason on hover) or hidden, and call it only when a presented template has a condition. Views that expose a template have the route in their execution plan (migration1.10.0-a22backfilled existing views). - Export route.
GET /v1/entities/{entity}/entries/export/{templateId}refuses an entry that does not match, and anymodeother than selected items for a conditioned template, with422 TEMPLATE_CONDITIONS_NOT_MET. The check runs before anything is rendered or queued. - Not gated. The Generate File From Template reaction action does not apply template conditions.
Version notes
Section titled “Version notes”| Feature | Since | Evidence |
|---|---|---|
Template parameters + display template models (TemplateParameter, EntityDisplayTemplate, ViewDisplayTemplate) | 1.4 | introduced in 1.4.0-alpha.01 |
Extended template export (exportFromTemplate / extended flag) | 1.6 | first tag 1.6.0 |
Background export (TemplateExportTypeEnum, ExportTemplateInBackgroundCommand, FileGeneratedEvent) | Long-standing | pre-1.2 |
Custom variables (additionalProperties / parseAdditionalProperties) | Long-standing | pre-1.2 |
GET /v1/templates/{id}/used | Long-standing | pre-1.2 |
| Streamed Excel template exports (500 entries per page) | 1.4 | first published on the 1.4 line; also delivered to the 1.6 and 1.8 lines |
| Selected virtual rows included in a template export | 1.4 | delivered to the 1.4, 1.6 and 1.8 lines |
| Templates tab on virtual entities | 1.6 | frontend, 1.6 and 1.8 lines |
Conditional export (query / criteria / nonMatchEntriesMode, status route, TEMPLATE_CONDITIONS_NOT_MET) | 1.10 | develop only (migration 1.10.0-a22) |
Per-template sensitive-data access policy (sensitiveDataAccessPolicy) | 1.10 | form control shown only when the entity has a sensitive field |
Notes and uncertainties
Section titled “Notes and uncertainties”TemplateParameterValueTypeEnum.Field(value2) exists in the model and enum, but the primary sources do not contain the code that resolves aFieldparameter into a runtime value; resolution appears to happen in a consumer not covered by the cited sources (likely the frontend or another service). TheFixed/Expressionsemantics are documented in the model JSDoc;Fieldsemantics are inferred from the enum name only.- The internal
templatesentity used byGET /v1/templates/{id}/used(withtemplate_type,template_details.template_header/footer,EMAIL_PART_TEMPLATE) is a data-entry-shaped structure whose full schema is not defined in the cited source files; field paths were read directly from the controller query. - Features marked Long-standing first shipped in pre-1.2 release tags; 1.2 is the earliest milestone in the tracked scheme, so the exact milestone of first availability is not distinguishable.
- The Excel path uses
xlsx-template’s default placeholder syntax; the exact delimiter is defined by that library, not by OSOS code, so it is described generically here.
Platform 1.10.0 · Backend 1.11.0-alpha.11 · Frontend 1.11.0-alpha.6 · Mobile 1.10.2 · Chart 1.11.8 · Gateway 2.6.11 · MCP 0.2.0 · Grafana DS 1.2.0Docs build 2026-11-27