Document Templates
Upload your own branded Microsoft Word and HTML templates and let Servantium merge in engagement and quote data automatically. Generate proposals and SOWs in seconds.
For a high-level comparison of how templates and data schemas differ, see the Templates vs. Data Dictionaries overview.
Quickstart
Navigate to Settings > Document Templates to upload, code, and manage your organization’s document templates.
In-Depth
Servantium uses standard Microsoft Word (DOCX) files and generated HTML code as templates. This allows you to maintain your brand’s exact styling, typography, and layout while automating the insertion of data.
Creating and Uploading
- Design your template in Microsoft Word, or use the HTML editor.
- Use Merge Fields to indicate where data should be inserted (e.g.,
{{engagement.name}},{{quote.total}}). - In Servantium, go to Settings > Document Templates.
- Click the Add (plus) icon in the table header. The system instantly generates a new template and redirects you directly to its workspace.
- On the template screen, rename the template to match its purpose.
- Optionally upload an Example Document (Word or PDF). The system securely stores this via internal Google Cloud Storage (
gs://) URIs and provides it to the AI document templating agent as reference context. If you do not provide an example document, the system will warn you prior to generation that the AI might not produce a good result. - Upload your master DOCX file, or configure raw markup directly in the HTML code editor.
- Link an existing Data Specification using the dropdown in the template details section.
Code Editor & Formatting
When editing HTML templates, the workspace includes a dedicated code editor with Jinja syntax highlighting for variables ({{ ... }}), control statements ({% ... %}), and comments ({# ... #}).
- Saving: Press
Ctrl+S(orCmd+Son Mac) or click Save in the toolbar to save your changes. - Auto-Formatting: Click the magic wand icon or press
Shift+Alt+F(orCtrl+Shift+I) to clean and indent your HTML, CSS, and Jinja tags using the built-in formatter. - Word Wrap: Click the word wrap toggle icon in the editor toolbar to switch between wrapped text and horizontal scrolling.
- In-Template Search: Press
Ctrl+F(orCmd+F) to search within the code. Navigating search matches automatically scrolls both vertically and horizontally to center the active match. - Keyboard Shortcuts: Pressing
Tabinserts two spaces instead of shifting focus. PressEscapeto quickly unfocus the editor.
Unsaved Changes & Live Preview
Local edits trigger an Unsaved Changes badge in the editor and preview pane.
- Refresh Preview: Click Refresh Preview (refresh icon) in the preview pane to render your latest uncommitted code changes in the iframe preview.
- Exit Safeguards: Navigating away with unsaved edits opens a confirmation prompt allowing you to keep editing or discard changes.
- AI Overwrite Protection: If a newly generated AI template arrives while you have local unsaved edits, a conflict dialog prompts you to overwrite or keep editing.
Data Specifications & Running Headers
Every document template uses a Data Specification to dictate data retrieval rules.
- Data Spec Link: Select a Data Spec from the details bar to map variables into your template. Opening dropdown menus temporarily pauses the live preview to prevent pointer click issues.
- Running Headers: For multi-page PDF generation, running headers use the Gotenberg Table Layout Wrapper pattern (
<table class="doc-wrapper"><thead class="doc-header-group">). This repeats the header natively across printed pages with explicit border and padding isolation, avoiding content overlaps and invalid fixed offsets. Cover pages placed before the table wrapper suppress running headers automatically. - Merge Tag Extraction: Tag extraction automatically detects custom list properties (e.g.,
quote['customData']['timeline']) with inferred column structures, expands mapped section attributes (e.g.,quote['sections'] | map(attribute=...)) into per-section tags, supports Jinja whitespace control syntax ({%-,-%},{{-,-}}), and ignores template-scoped variables declared with{% set %}statements alongside loop-local variables and Jinja built-ins (likeloop.index) so they are not incorrectly surfaced as top-level document merge tags.
Data Specifications (Data Spec)
Every document template uses a Data Spec to define exactly what information it needs. Data Specs are standalone, reusable entities managed in Settings > Data Specifications. They feature unique names, categorical tags, and can target arbitrary root objects (like an Account, Contact, or Project Plan).
Because Data Specs are independent, multiple document templates can share the exact same data routing rules. To connect a Data Spec to a document template, simply select it from the Data Specification dropdown on the template’s detail form. The backend automatically synchronizes the document template’s target collection to match its linked Data Spec. If the underlying Data Spec is updated later, all linked templates are automatically kept in sync.
When opening the Data Specification dropdown or other modal dialogs, the live HTML preview temporarily pauses and displays a placeholder. This ensures your dropdown menus remain fully clickable over the document preview area. The live preview resumes automatically as soon as the menu is closed.
If you use the AI Template Generator, the AI’s Schema Orchestrator automatically builds a complete Data Spec for you (or intelligently reuses an existing matching one), saves it to your organization’s library, and links it to the template.
When manually configuring raw HTML templates, always use strict bracket notation for dictionary properties and nested structures (e.g., engagement['customData']['clientName'], NEVER engagement.customData.clientName). Document merge payloads provide subcollections as dictionary maps, so you must iterate over them using .values() (e.g., {% for item in (project_plan_items.values() if project_plan_items is mapping else (project_plan_items or [])) | sort(attribute='order') %}). Never attempt to access item arrays directly on parent documents (like project_plan['items']), as child items reside directly under their subcollection source. Never append ['customData'] to local loop iteration variables (e.g., inside a loop, use item['field'], not item['customData']['field']). You must use the exact property keys as defined in your Data Dictionary without altering casing. Using dot notation for dictionary keys like items, keys, or values causes fatal rendering crashes because Jinja2 resolves them to built-in Python methods. Additionally, always use proper Jinja closing tags (e.g., {% endif %} and {% else %}), use safe Jinja defaults (e.g., {{ engagement['customData']['var'] | default('') }}), and reference snippets with single clean tags (e.g., {{ snippets['Name'] }}) rather than complex {% if %} fallback chains. Never pass nested dictionary lookups as arguments inside default(...) filters, as Jinja evaluates them eagerly and will crash if the dictionary is undefined.
AI Template Generation
Servantium features AI agents that convert example documents (PDF or Word) into reusable HTML/CSS templates. The AI analyzes structural headings, extracts header logos, registers dynamic variables into Data Dictionaries, and formats repeating lists into semantic Jinja loops. When requesting AI edits for specific sections, the generation engine scopes updates to the targeted sections and ignores non-fatal warnings on untargeted areas. Manual edits saved directly to a template in the database are automatically re-hydrated into active AI sessions.
- Clean Sessions & Restarts: When you initiate AI generation, the system prompts you to “Start Fresh.” This explicitly forces a complete pipeline restart and clears any previous active AI session to ensure your new generation pipeline begins from a completely clean state. Opening the AI generation dialog also explicitly cancels active debounce saves to prevent conflicting state updates.
- Schema Orchestration: The AI dynamically analyzes your document to distribute the workload across specialized sub-agents. It strictly cross-references numbered instructions against the document’s actual Table of Contents or headings to resolve exact titles, preventing the hallucination of generic placeholder headings (like “Scope” or “Deliverables”) when actual titles exist. The AI automatically enforces standard document hierarchy, ensuring a Cover Page always precedes the Table of Contents. The system uses numbering-insensitive matching (e.g., seamlessly matching “1.0 Executive Summary” with “Executive Summary”) to ensure discrepancies don’t result in duplicate sections. It automatically extracts small reusable custom data, identifies complex pricing formulas for quote templates, maps reusable narrative blocks into snippets, and builds a comprehensive Data Spec. Before creating a new Data Spec, the AI actively searches your organization for existing specifications matching the base entity and reuses them to prevent duplicates. If no structure can be determined, it gracefully falls back to a single unified section to prevent generation failures.
- Data Dictionary Registration: Before registering new custom data variables, the AI automatically reviews your entire active data schema across all entities. If a matching property already exists (like
job_title), it intelligently reuses the existing field to prevent duplicates. If no match exists, it calls a system tool to officially register the new property in your Data Dictionaries, automatically inferring the correct data type. The generation pipeline also automatically flattens eager nested defaults, converts dot notation to bracket access, and corrects minor casing mismatches in generated Jinja tags across the entire document prior to saving. - Multimodal Extraction: When you upload an example document, the backend multimodal AI processes the file, extracting text via OCR (with a robust XML fallback parser for Word documents) and identifying assets. It natively extracts corporate logos and banner graphics directly from Word document running headers and footers, integrating them automatically into your final HTML wrapper. The system also extracts OpenXML styling metadata (font colors, table shading) directly from Word documents to generate a perfectly matched global CSS stylesheet. The pipeline automatically pre-fetches these structural blueprints and assets, injecting them directly into the Developer agents to prevent AI hallucinations.
- Surgical Micro-Editing: When refining existing templates based on feedback, the AI uses surgical HTML micro-editing. If feedback targets global document styles (like table margins or font sizes), the pipeline isolates the global CSS block, applies targeted search-and-replace patches, and completely skips regenerating the HTML sections (Zero-LLM Re-use). Rather than rewriting entire sections and risking layout regressions, it generates targeted patches that preserve your surrounding HTML and scoped CSS byte-for-byte.
- Side-by-Side Code Editor: The workspace dynamically adapts to your screen size. On desktop, it displays a side-by-side layout containing your original reference document, the HTML code editor, and a live HTML preview. On mobile, these panels are organized into tabs. This dedicated code editor provides an improved developer experience for configuring and refining the final template markup, and features a live preview that updates in real-time as you code.
- Parallel HTML Generation: To handle massive documents efficiently, the AI outlines the structural sections and spins up specialized Developer and QA agents to build them in parallel. To ensure precise content preservation, Developer agents are strictly grounded in the exact source text of the specific section they are building. The extraction engine intelligently bypasses Table of Contents pages to ensure only the actual body content is used. They can intelligently render document title headers and status summary callout grids matching the original layout. They are explicitly prohibited from generating raw narrative text, and from inventing dashboard metrics, KPIs, or arbitrary widgets that do not appear in the source document.
- Visual, Syntax & Data QA: The QA agents enforce a mandatory, explicit Jinja syntax check and local mock rendering test as their very first step. The pipeline evaluates every individual Jinja tag against a strict undefined environment to catch nested evaluation errors during rendering tests. The multimodal Visual QA process explicitly factors in active user feedback and strictly enforces table structure fidelity, verifying that generated HTML columns exactly match the headers and status badge styling in your reference image. If any invalid root objects, unclosed tags, or snippet fallback chains are found, the section is immediately rejected. The pipeline uses an Evaluator-Refiner loop that isolates and iteratively repairs only the rejected sections. To prevent infinite loops, it enforces a strict 10-attempt circuit breaker.
- Semantic Tables & Lists: When the AI encounters tabular data or repeating lists—such as project plan tasks, deliverables, custom
Listproperties, or milestones—it is explicitly trained to build clean, semantic HTML tables and iterate over the items dynamically using Jinja loops, rather than falling back to hardcoded static rows. - Interactive Workflow Tracking: During generation, an interactive, zoomable directed graph visually tracks pipeline progress. The graph automatically adapts to your system’s light or dark mode preferences. Upon completion (or if an error occurs), the conversational summary and diagnostic messages appear inline alongside the graph as selectable text, making it easy to copy diagnostic information.
AI Snippet Extraction
During generation, the AI extracts content into distinct snippet types based strictly on formatting complexity:
- Plain Text (
text/ai): Unformatted plain text boilerplate or dynamic AI instructions. The AI strictly uses these types when no formatting (bolding, lists, HTML) is required. - Markdown (
md/aimd): Static or dynamic Markdown text. Used whenever the snippet requires basic text formatting such as bold, italics, bullet lists, numbered lists, blockquotes, or headings. - HTML (
aiHtml/html): Complex, dynamic diagrams and structural formatting. The AI strictly uses this type for snippets requiring advanced UI features like styled tables, embedded images, custom CSS, or multi-column grids. - Intelligent Snippet Reuse: The AI actively searches your organization’s schema for existing snippets with matching names or semantic overlap. If a match is found, it reuses the existing snippet ID to prevent duplicate definitions.
- Section Body Extraction: When snippets correspond to document sections (like “Objectives” or “General Assumptions”), the AI bypasses generic generation. Instead, it extracts the genuine section body narrative directly from your source document, cleanly strips any DOCX styling artifacts, and converts the content into reusable Markdown. If the document includes a Table of Contents, the AI automatically extracts and configures a distinct markdown snippet for every major narrative section.
How it works
When a user generates a document from a record (like an engagement, quote, or project plan), the backend merging engine:
- Fetches the template.
- Scans for all merge fields.
- Resolves those fields using data mapped from the active data specification.
- Generates a final, ready-to-send PDF or DOCX file.
For a complete list of available merge fields and advanced formatting options (like tables and conditional logic), refer to the Documents Guide.
Related
Need more help?
Our support team is available to assist you.
Contact Support