Skip to main content
Back to ScopeForged

ScopeForged Documentation

Technical documentation, guides, and feature references for the ScopeForged client portal.

Files & Documents/Document Templates

Document Templates Guide

Last Updated: 2026-01-13 Status: Implemented (Enhanced) Plan References:

  • 045-document-generation-templates.md
  • 062-document-templates-enhancement.md
  • 089-document-templates-improvement.md

Plan 089 Enhancements (2026-01-13):

  • Template Marketplace for sharing and installing templates
  • Template categories with TemplateCategory model
  • Import/export templates as JSON
  • WYSIWYG template editor component
  • TemplateExportService for bundling and importing

Overview

The Document Templates system allows administrators to create reusable document templates with variable placeholders. These templates can generate professional documents such as proposals, contracts, statements of work, and reports by merging with client, project, or invoice data.


Table of Contents

  1. Accessing Templates
  2. Features
  3. How to Use
  4. Template Marketplace
  5. Import/Export Templates
  6. Template Variables
  7. Template Components
  8. WYSIWYG Editor
  9. Template Validation
  10. Technical Architecture
  11. Related Features

Accessing Templates

Access PointLocationURLRole
Template LibraryAdmin sidebar/admin/documents/templatesAdmin
Create TemplateTemplates page/admin/documents/templates/createAdmin
Edit TemplateTemplate row/admin/documents/templates/{id}/editAdmin
Generate DocumentTemplate/Project pageModal actionAdmin
Generated DocumentsDocuments section/admin/documentsAdmin

Permissions

ActionAdminClient User
View templates
Create templates
Edit templates
Delete templates
Generate documents
View generated docs✅ (shared)
Download documents✅ (shared)

Features

Template Management

  • Create and edit templates
  • Rich text editor (WYSIWYG)
  • Template categories
  • Template versioning
  • Clone templates

Variable System

  • Client variables
  • Project variables
  • Invoice variables
  • User variables
  • Custom variables
  • Date/time variables

Document Generation

  • Merge template with data
  • PDF output
  • Word document output
  • HTML preview
  • Batch generation

Document Library

  • Store generated documents
  • Version tracking
  • Share with clients
  • Digital signatures (optional)

How to Use

Creating a Template

  1. Navigate to Admin → Documents → Templates
  2. Click "Create Template"
  3. Fill in template details:
    • Name: Template name (e.g., "Service Agreement")
    • Category: Select or create category
    • Description: Internal description
  4. Write template content in editor
  5. Insert variables using toolbar or {{variable}} syntax
  6. Click "Save Template"

Using Variables in Templates

Insert variables using double curly braces:

Dear {{client.contact_name}},

Thank you for choosing {{company.name}}. We are pleased to present
this proposal for {{project.name}}.

Project Start Date: {{project.start_date}}
Estimated Budget: {{project.budget | currency}}

Best regards,
{{user.name}}
{{company.name}}

Generating a Document

From Template:

  1. Navigate to Admin → Documents → Templates
  2. Click "Generate" on desired template
  3. Select data source:
    • Client
    • Project
    • Invoice
  4. Preview generated document
  5. Click "Generate PDF" or "Generate Word"
  6. Document saved to library

From Project:

  1. Navigate to Admin → Projects → [Project]
  2. Click "Generate Document"
  3. Select template
  4. Review merged preview
  5. Generate and save

Editing a Template

  1. Navigate to Admin → Documents → Templates → [Template]
  2. Click "Edit"
  3. Modify content or variables
  4. Click "Save"
  5. Previous version saved automatically

Sharing Documents with Clients

  1. Navigate to Admin → Documents
  2. Find generated document
  3. Click "Share with Client"
  4. Document appears in client portal
  5. Client can view and download

Template Marketplace

The Template Marketplace allows admins to share templates publicly and install templates created by others.

Accessing Marketplace

Access PointLocationURL
MarketplaceTemplates page/admin/templates/marketplace
Share TemplateTemplate actionsShare button
My TemplatesTemplates index/admin/documents/templates

Browsing Templates

  1. Navigate to Admin → Templates → Marketplace
  2. Filter by category (left sidebar)
  3. Search by name or description
  4. Sort by: Popular, Newest, or Name
  5. Click "Preview" to view details
  6. Click "Install" to add to your library

Sharing Templates

Share your templates with other admins:

  1. Navigate to Admin → Documents → Templates
  2. Select a template
  3. Click "Share to Marketplace"
  4. Template becomes public
  5. Track installs from marketplace

Unsharing Templates

  1. View your shared template
  2. Click "Remove from Marketplace"
  3. Template becomes private again

Template Categories

Categories organize marketplace templates:

CategoryDescription
ProposalsClient proposals
ContractsService agreements
SOWStatements of work
ReportsProject reports
LettersCorrespondence

Import/Export Templates

Exporting Templates

Export a single template:

  1. View template in marketplace
  2. Click "Export JSON"
  3. Template downloads as .json file

Export format includes:

  • Template name and description
  • Content HTML
  • Variables configuration
  • Layout options
  • Font configuration
  • Category (by slug)

Importing Templates

Import a template file:

  1. Navigate to Admin → Templates → Marketplace
  2. Use "Import Template" form (left sidebar)
  3. Select .json file
  4. Click "Import"
  5. Template added to your library

Export Bundle

Export multiple templates at once via API:

$service = app(TemplateExportService::class);
$json = $service->exportBundle([$id1, $id2, $id3]);

Import Bundle

$templates = $service->importBundle($jsonContent);
// Returns array of imported DocumentTemplate models

Export Format

{
    "meta": {
        "version": "1.0",
        "exported_at": "2026-01-13T12:00:00Z",
        "source": "Client Portal"
    },
    "template": {
        "name": "Template Name",
        "category": "proposal",
        "category_slug": "proposals",
        "description": "Template description",
        "content": "<h1>Template Content</h1>",
        "variables": {},
        "layout_options": {},
        "font_config": {}
    }
}

WYSIWYG Editor

The visual template editor (<x-template-editor>) provides a rich editing experience.

Using the Component

<x-template-editor
    :template="$template"
    :variables="$availableVariables"
    name="content"
/>

Editor Features

FeatureDescription
Text FormattingBold, italic, underline
HeadingsH1, H2, H3, paragraph
ListsBullet and numbered lists
AlignmentLeft, center, right
Insert VariableDropdown with all variables
Insert Table3x2 default table
Insert LinkURL with selected text
Insert ImageImage by URL
Undo/RedoEdit history
View ToggleVisual / HTML source

Keyboard Shortcuts

ShortcutAction
Ctrl+BBold
Ctrl+IItalic
Ctrl+UUnderline
Ctrl+ZUndo
Ctrl+YRedo

Variable Insertion

Variables are grouped by category:

  • Company: name, address, phone, email
  • Client: company_name, contact_name, email
  • Project: name, description, dates, budget
  • Invoice: number, items, totals
  • Date: today, year, month

Insert via dropdown or type {{variable.name}} directly.


Template Variables

Client Variables

VariableDescriptionExample
{{client.company_name}}Company nameAcme Corp
{{client.contact_name}}Contact nameJohn Smith
{{client.email}}Email addressjohn@acme.com
{{client.phone}}Phone number555-1234
{{client.address}}Street address123 Main St
{{client.city}}CityNew York
{{client.state}}StateNY
{{client.zip}}ZIP code10001
{{client.full_address}}Complete addressFull formatted

Project Variables

VariableDescriptionExample
{{project.name}}Project nameWebsite Redesign
{{project.description}}DescriptionFull description
{{project.status}}Current statusActive
{{project.start_date}}Start dateJan 15, 2026
{{project.due_date}}Due dateMar 15, 2026
{{project.budget}}Budget amount15000.00
`{{project.budgetcurrency}}`Formatted

Invoice Variables

VariableDescriptionExample
{{invoice.number}}Invoice numberINV-2026-001
{{invoice.status}}StatusSent
{{invoice.issue_date}}Issue dateJan 20, 2026
{{invoice.due_date}}Due dateFeb 20, 2026
{{invoice.subtotal}}Subtotal$5,000.00
{{invoice.tax}}Tax amount$400.00
{{invoice.total}}Total$5,400.00
{{invoice.items}}Line items tableTable HTML

Company Variables

VariableDescription
{{company.name}}Company name
{{company.address}}Company address
{{company.phone}}Company phone
{{company.email}}Company email
{{company.website}}Company website
{{company.logo}}Logo image tag

User Variables

VariableDescription
{{user.name}}Current user name
{{user.email}}Current user email
{{user.title}}User title/role

Date Variables

VariableDescriptionExample
{{date.today}}Current dateJan 25, 2026
{{date.now}}Current datetimeJan 25, 2026 2:30 PM
{{date.year}}Current year2026
{{date.month}}Current monthJanuary

Variable Formatters

FormatterUsageResult
currency`{{valuecurrency}}`
date`{{valuedate}}`
uppercase`{{valueuppercase}}`
lowercase`{{valuelowercase}}`
default`{{valuedefault:'N/A'}}`

Template Components

Template components are reusable building blocks that can be inserted into templates. They help maintain consistency across documents and reduce duplication.

Accessing Components

  • Navigation: More > Template Components
  • URL: /admin/templates/components
  • Permissions: Admin only

Component Categories

CategoryDescription
HeaderDocument headers, letterheads
FooterDocument footers, signature blocks
TableData tables, invoice items
SectionContent sections, dividers
SignatureSignature blocks
DividerVisual separators

Creating a Component

  1. Navigate to More > Template Components
  2. Click "Create Component"
  3. Fill in details:
    • Name: Component name
    • Category: Select category
    • Description: Usage description
    • Content: HTML with variables
  4. Click "Create Component"

Using Components in Templates

Insert components using the component library in the template editor:

  1. Open template editor
  2. Click "Insert Component"
  3. Select component from library
  4. Component HTML is inserted at cursor

Example Components

Company Letterhead:

<div class="letterhead">
    <img src="{{company.logo_url}}" class="logo" />
    <div class="company-info">
        <h1>{{company.name}}</h1>
        <p>{{company.address}}</p>
        <p>{{company.phone}} | {{company.email}}</p>
    </div>
</div>

Signature Block:

<div class="signature-block">
    <div class="signature-line"></div>
    <p>{{user.name}}</p>
    <p>{{user.title}}</p>
    <p>{{date.today}}</p>
</div>

Template Validation

Templates can be validated to check for errors before use.

Validation Checks

CheckDescription
Unknown variablesVariables not in registry
HTML validityValid HTML structure
Unclosed loopsMissing {{/each}} tags
Unclosed conditionalsMissing {{/if}} tags
Render errorsTemplate can be rendered

Using Validation

  1. Open template editor
  2. Click "Validate" button
  3. View validation results:
    • Errors (must fix)
    • Warnings (review recommended)

Variable Registry

The system maintains a registry of all available variables with:

  • Variable key and syntax
  • Description
  • Example value
  • Formatter support

Access variables in editor via the Variable sidebar or search.


Technical Architecture

Models

DocumentTemplate Model: app/Models/DocumentTemplate.php

class DocumentTemplate extends Model
{
    protected $fillable = [
        'name',
        'category_id',
        'description',
        'content',
        'format',
        'is_active',
        'version',
    ];

    protected $casts = [
        'is_active' => 'boolean',
        'version' => 'integer',
    ];
}

GeneratedDocument Model: app/Models/GeneratedDocument.php

class GeneratedDocument extends Model
{
    protected $fillable = [
        'template_id',
        'documentable_type',
        'documentable_id',
        'filename',
        'path',
        'format',
        'is_client_visible',
        'generated_by',
    ];
}

Services

ServiceLocationPurpose
VariableRegistryapp/Services/Templates/VariableRegistry.phpManages available variables
TemplateRendererapp/Services/Templates/TemplateRenderer.phpRenders templates with data
TemplatePreviewServiceapp/Services/Templates/TemplatePreviewService.phpGenerates previews
TemplateValidatorapp/Services/Templates/TemplateValidator.phpValidates templates
TemplateExportServiceapp/Services/Templates/TemplateExportService.phpImport/export templates

TemplateExportService: Template import/export and bundling

$service = app(TemplateExportService::class);

// Export single template
$data = $service->export($template);
$json = $service->toJson($template);

// Import template
$template = $service->fromJson($jsonContent);

// Export/import bundles
$bundleJson = $service->exportBundle([$id1, $id2]);
$templates = $service->importBundle($bundleJson);

// Download response
return $service->downloadResponse($template);

VariableRegistry: Centralized variable management

$registry->register('company', [
    'company.name' => [
        'description' => 'Company name',
        'example' => 'Acme Corp',
    ],
    // ...
]);

// Get all variables
$variables = $registry->getAll();

// Search variables
$results = $registry->search('client');

TemplateRenderer: Variable replacement and template rendering

$renderer = app(TemplateRenderer::class);
$html = $renderer->render($template->content, $data);

TemplateValidator: Template validation

$validator = app(TemplateValidator::class);
$result = $validator->validate($content);

if (!$result->valid) {
    foreach ($result->errors as $error) {
        // Handle errors
    }
}

Controller

Location: app/Http/Controllers/Admin/DocumentTemplateController.php

MethodRouteDescription
index()GET /admin/documents/templatesList templates
create()GET /admin/documents/templates/createCreate form
store()POST /admin/documents/templatesSave template
show()GET /admin/documents/templates/{template}View template
edit()GET /admin/documents/templates/{template}/editEdit form
update()PUT /admin/documents/templates/{template}Update template
destroy()DELETE /admin/documents/templates/{template}Delete template
preview()GET /admin/documents/templates/{template}/previewPreview merge
duplicate()POST /admin/documents/templates/{template}/duplicateClone template

Routes

// Document Templates
Route::resource('documents/templates', DocumentTemplateController::class)->names('documents.templates');
Route::get('documents/templates/{template}/preview', [DocumentTemplateController::class, 'preview']);
Route::post('documents/templates/{template}/duplicate', [DocumentTemplateController::class, 'duplicate']);
Route::patch('documents/templates/{template}/toggle-active', [DocumentTemplateController::class, 'toggleActive']);

// Generated Documents
Route::resource('documents', GeneratedDocumentController::class);
Route::get('documents/{document}/pdf', [GeneratedDocumentController::class, 'streamPdf']);
Route::get('documents/{document}/pdf/download', [GeneratedDocumentController::class, 'downloadPdf']);
Route::post('documents/{document}/regenerate', [GeneratedDocumentController::class, 'regenerate']);

Database Tables

Table: document_templates

ColumnTypeDescription
idbigintPrimary key
namestringTemplate name
category_idbigintCategory FK
descriptiontextDescription
contentlongtextTemplate HTML
formatstringDefault format
is_activebooleanActive status
versionintegerVersion number
created_attimestampCreated date
updated_attimestampUpdated date

Table: generated_documents

ColumnTypeDescription
idbigintPrimary key
template_idbigintSource template
documentable_typestringPolymorphic type
documentable_idbigintPolymorphic ID
filenamestringFile name
pathstringStorage path
formatstringPDF/DOCX/HTML
is_client_visiblebooleanShared with client
generated_bybigintUser who generated
created_attimestampGenerated date

Template Examples

Service Proposal

<h1>Service Proposal</h1>
<p>Date: {{date.today}}</p>

<h2>Prepared For:</h2>
<p>
{{client.company_name}}<br>
{{client.contact_name}}<br>
{{client.full_address}}
</p>

<h2>Project Overview</h2>
<p>{{project.description}}</p>

<h2>Timeline</h2>
<p>Start Date: {{project.start_date | date}}</p>
<p>Completion: {{project.due_date | date}}</p>

<h2>Investment</h2>
<p>Total: {{project.budget | currency}}</p>

Invoice Template

<table>
{{invoice.items}}
</table>
<p>Total Due: {{invoice.total | currency}}</p>

Dependencies

FeatureRelationship
PDF GenerationPDF output
Client ManagementClient data
Project ManagementProject data
InvoicingInvoice data

Complementary Features

FeatureDescription
File SharingDocument storage
NotificationsSend documents
Activity LoggingTrack generation

Best Practices

For Template Creation

  1. Use descriptive names for templates
  2. Test with sample data before production use
  3. Include default values for optional variables
  4. Keep formatting consistent
  5. Version templates before major changes

For Developers

  1. Cache template parsing for performance
  2. Validate variables before rendering
  3. Escape user content to prevent XSS
  4. Handle missing data gracefully

Troubleshooting

IssueSolution
Variable not replacedCheck variable syntax and data source
PDF rendering issuesVerify HTML is valid
Missing dataEnsure model relationships loaded
Slow generationEnable caching, optimize queries

See Also