Skip to main content

Working with Templates

Learn how to use templates when generating documents via the RenderDoc API.

Overview

Templates in RenderDoc are pre-designed document formats created in the dashboard. When generating documents via API, you reference these templates by their ID and provide variables for personalization.

info

Template Management: Templates can be created, updated, and deleted via both the Dashboard UI and JWT-authenticated API endpoints. The Dashboard provides a visual designer for easier template creation, while the API allows programmatic management for automation and integration purposes.


How Templates Work

1. Create Templates

Templates can be created in two ways:

Option A: Dashboard (Recommended for Design)

  • Navigate to Templates in the dashboard
  • Click Create Template
  • Use the visual drag-and-drop designer
  • Define variables for dynamic content
  • Save and publish your template

See the Templates User Guide for detailed instructions.

Option B: API (For Automation)

  • Use JWT-authenticated API endpoints
  • Programmatically create and manage templates
  • Ideal for CI/CD pipelines and automated workflows
  • Requires template schema knowledge

See the API Reference - Templates for API documentation.

2. Use Templates for Document Generation

Once templates are created, reference them in API calls:

{
templateId: 'tmpl_invoice', // Required - references dashboard template
format: 'pdf', // or 'xlsx'
variables: { // Fills in template placeholders
invoiceNumber: 'INV-001',
customerName: 'Acme Corp',
amount: 1250.00
}
}

Template Types

RenderDoc supports two output formats from templates:

PDF Templates

Used for generating professional PDF documents:

  • Text, headings, paragraphs
  • Images and logos
  • Tables for data display
  • Conditional blocks
  • Loops for repeating content
  • Native charts (bar, line, pie, area, scatter)
  • Page breaks and headers/footers

Usage:

curl https://api.renderdoc.dev/api/v1/documents/generate \
-H "Authorization: Bearer rd_sk_abc123..." \
-H "Content-Type: application/json" \
-X POST \
-d '{
"templateId": "tmpl_invoice",
"format": "pdf",
"variables": { "invoiceNumber": "INV-001" }
}'

Excel Templates

Used for generating Excel spreadsheets:

  • All PDF components plus:
  • Native charts with Excel interactivity
  • Advanced table formatting with calculated columns
  • Multiple sheets
  • Formula support

Usage:

const result = await client.documents.generate({
templateId: 'tmpl_monthly_report',
format: 'xlsx',
variables: {
reportMonth: 'January 2025',
data: [
{ category: 'Sales', amount: 50000 },
{ category: 'Expenses', amount: 30000 }
]
}
});

Using Template Variables

Variable Syntax

Templates use Handlebars syntax for variables:

Invoice #{{invoiceNumber}}

Customer: {{customerName}}
Total: ${{orderTotal}}

Providing Variable Values

Pass variable values in the variables object:

const response = await fetch('https://api.renderdoc.dev/api/v1/documents/generate', {
method: 'POST',
headers: {
'Authorization': `Bearer ${apiKey}`,
'Content-Type': 'application/json'
},
body: JSON.stringify({
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
invoiceNumber: 'INV-001',
customerName: 'Acme Corp',
orderTotal: 99.99
}
})
});

Variable Types

Templates can use different variable types:

TypeExampleDescription
String{{customerName}}Text values
Number{{orderTotal}}Numeric values
Boolean{{isPremium}}True/false values
Array{{#each items}}...{{/each}}Lists of items
Object{{customer.name}}Nested data

Complex Variables Example

{
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
// Simple values
invoiceNumber: 'INV-12345',
issueDate: '2025-11-07',

// Object values
customer: {
name: 'John Doe',
company: 'Acme Corp',
email: '[email protected]'
},

// Array values
items: [
{ name: 'Product A', quantity: 2, price: 49.99 },
{ name: 'Product B', quantity: 1, price: 29.99 }
],

// Calculated values
subtotal: 129.97,
tax: 13.00,
total: 142.97
}
}

Required vs Optional Variables

Required Variables

Templates can define required variables. If you don't provide them, the API will return an error:

{
"statusCode": 400,
"code": "ERR_VALID_005",
"message": "Required field is missing",
"relatedInfo": {
"variable": "invoiceNumber",
"templateId": "tmpl_invoice"
}
}

Solution: Provide all required variables:

{
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
invoiceNumber: 'INV-001', // Required
customerName: 'John Doe', // Required
amount: 99.99 // Required
}
}

Optional Variables

Optional variables can be omitted. The template handles missing values gracefully:

Invoice #{{invoiceNumber}}{{#if poNumber}} (PO: {{poNumber}}){{/if}}

Conditional Content

Templates support conditional blocks using Handlebars helpers:

Template Design (Dashboard)

{{#if isPremium}}
<p>Premium Customer - Priority Support Included</p>
{{else}}
<p>Standard Customer</p>
{{/if}}

API Usage

{
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
isPremium: true // Controls conditional block
}
}

Loops and Repeating Content

Templates can loop through arrays of data:

Template Design (Dashboard)

<h2>Line Items</h2>
<table>
{{#each items}}
<tr>
<td>{{this.name}}</td>
<td>{{this.quantity}}</td>
<td>${{this.price}}</td>
</tr>
{{/each}}
</table>

API Usage

{
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
items: [
{ name: 'Product A', quantity: 2, price: 49.99 },
{ name: 'Product B', quantity: 1, price: 29.99 },
{ name: 'Product C', quantity: 3, price: 19.99 }
]
}
}

Finding Template IDs

Via Dashboard

  1. Navigate to Templates in the dashboard
  2. Click on a template to view details
  3. Copy the Template ID from the details page

Template IDs follow the format: tmpl_xxxxxxxxxx

Naming Convention

Use descriptive template IDs for clarity:

  • tmpl_invoice - Invoice generation
  • tmpl_monthly_report - Monthly report
  • tmpl_contract - Contract document
  • tmpl_receipt - Receipt generation

Template Errors

Template Not Found

{
"statusCode": 404,
"code": "ERR_TMPL_001",
"message": "Template not found",
"relatedInfo": {
"templateId": "tmpl_invalid"
}
}

Solution: Verify the template ID exists in your dashboard.

Template Not Published

{
"statusCode": 400,
"code": "ERR_TMPL_021",
"message": "Template has no published version",
"relatedInfo": {
"templateId": "tmpl_invoice",
"status": "draft"
}
}

Solution: Publish the template in the dashboard before using it via API.

Missing Required Variable

{
"statusCode": 400,
"code": "ERR_VALID_005",
"message": "Required field is missing",
"relatedInfo": {
"variable": "invoiceNumber",
"templateId": "tmpl_invoice"
}
}

Solution: Provide all required variables in the variables object.


Best Practices

1. Use Descriptive Template Names

Good:

  • tmpl_invoice_standard
  • tmpl_report_monthly
  • tmpl_contract_service

Bad:

  • tmpl_001
  • tmpl_test
  • tmpl_doc

2. Define Clear Variable Names

Good:

{
variables: {
customerFirstName: 'John',
invoiceNumber: '12345',
totalAmount: 99.99
}
}

Bad:

{
variables: {
fn: 'John',
in: '12345',
t: 99.99
}
}

3. Validate Variable Data

Always validate data before generating:

function validateInvoiceData(invoice) {
if (!invoice.number) throw new Error('Invoice number required');
if (!invoice.customer.name) throw new Error('Customer name required');
if (invoice.items.length === 0) throw new Error('Invoice must have items');
return true;
}

// Use it
validateInvoiceData(invoiceData);

await client.documents.generate({
templateId: 'tmpl_invoice',
format: 'pdf',
variables: invoiceData
});

4. Use Template Versioning

When templates are updated in the dashboard, the API automatically uses the latest published version. To ensure consistency:

  • Test template changes in a non-production environment first
  • Use separate templates for different environments (e.g., tmpl_invoice_dev, tmpl_invoice_prod)
  • Document template changes in your version control system

5. Handle Missing Optional Variables

Design templates to handle missing optional variables gracefully:

{{#if companyLogo}}
<img src="{{companyLogo}}" />
{{/if}}

6. Keep Templates Simple

  • Break complex documents into smaller, reusable templates
  • Use consistent naming conventions
  • Document required and optional variables
  • Test templates with various data combinations

Testing Templates

Test with Real Data

Always test templates with realistic data:

// Production-like test data
const testVariables = {
invoiceNumber: 'INV-TEST-001',
customer: {
name: 'Test Customer',
company: 'Test Corp'
},
items: [
{ name: 'Product A', quantity: 2, price: 49.99 },
{ name: 'Product B', quantity: 1, price: 29.99 }
],
total: 129.97
};

// Generate test document
const result = await client.documents.generate({
templateId: 'tmpl_invoice',
format: 'pdf',
variables: testVariables
});

console.log('Test document:', result.downloadUrl);

Testing Tips

When testing templates:

  • Use the template preview in the dashboard
  • Generate documents with various data combinations
  • Test edge cases (empty arrays, long text, special characters)
  • Verify formatting across different output formats

See Authentication for API key details.


Common Use Cases

Invoice Generation

{
templateId: 'tmpl_invoice',
format: 'pdf',
variables: {
invoiceNumber: 'INV-12345',
issueDate: '2025-01-15',
customer: {
name: 'John Doe',
company: 'Acme Corp',
address: '123 Main St, New York, NY'
},
items: [
{ name: 'Product A', quantity: 2, price: 49.99 },
{ name: 'Product B', quantity: 1, price: 29.99 }
],
subtotal: 129.97,
tax: 13.00,
total: 142.97
}
}

Monthly Report

{
templateId: 'tmpl_monthly_report',
format: 'xlsx',
variables: {
reportMonth: 'January 2025',
department: 'Sales',
metrics: [
{ category: 'Revenue', value: 150000, change: '+12%' },
{ category: 'Orders', value: 523, change: '+8%' },
{ category: 'Customers', value: 89, change: '+15%' }
],
summary: 'Strong growth across all metrics.'
}
}

Contract Document

{
templateId: 'tmpl_service_contract',
format: 'pdf',
variables: {
contractNumber: 'CON-2025-001',
effectiveDate: '2025-02-01',
clientName: 'Acme Corporation',
serviceTerm: '12 months',
monthlyFee: 5000,
services: [
'Consulting Services',
'Technical Support',
'Training Sessions'
]
}
}

Next Steps


Related: Generating Documents | Authentication | Templates User Guide