Dynamic Contracts
Learn how to create personalized, dynamic legal documents using Handlebars.js templating to customize terms based on user data.
Overview
ToughClicks supports dynamic contract rendering through Handlebars.js templating. This powerful feature allows you to:
- Personalize terms with user-specific information
- Conditionally show or hide clauses
- Dynamically populate contract fields
- Create adaptive legal agreements
Dynamic contracts enable you to maintain a single document template while rendering personalized versions for each user.
How It Works
- Create Template - Add Handlebars expressions to your document terms in the ToughClicks Management Portal
- Set Dynamic Data - Provide data to the JavaScript library before rendering
- Render - ToughClicks processes the template and displays personalized terms
Setting Up Dynamic Data
To use dynamic contracts, set your data before calling render():
import { ToughClicks } from '@toughclicks/js-client-sdk';
const tc = new ToughClicks(clientToken, packetId);
// Set dynamic data
tc.setDynamicData({
Person: {
Email: '[email protected]',
Name: 'Daniel Litvak',
Company: 'Acme Corporation'
}
});
// Configure display options
tc.setDisplayOptions({
containerId: 'tc-agreements',
signerId: '[email protected]'
});
// Render with dynamic data
tc.render();
Limits and Sanitization
Dynamic data has the same limits in the JavaScript library and the API:
| Rule | Limit |
|---|---|
| Size of the serialized JSON (UTF-8 bytes) | 60 KB (61,440 bytes) |
| Nesting | at most 10 levels of objects/arrays (the root object is level 1) |
| Keys | at most 100 in total, counting the keys of nested objects |
| Key names | at most 100 characters; keys starting with $ or ., and __proto__, constructor and prototype, are not allowed (the library drops them before sending; the API rejects them with a 400) |
setDynamicData() and setPacketDynamicData() return false when the data breaks a limit (enable debug mode to see which), instead of sending a request the API would reject. The library sends dynamic data in the body of a Render Packet request, so payloads larger than a URL allows are fine up to 60 KB. If the API does reject a request, the tc-internal-error event's message includes the API's reason, and event.detail.apiError.apiMessage holds it on its own.
Values are plain text. HTML tags are stripped from every string value before it is rendered or stored, so "<b>Ada</b>" renders as Ada. Put markup in the template, around the variable:
<p>Welcome, <strong>{{user.name}}</strong></p>
Use {{ }}, not {{{ }}}. Templates can't use Handlebars' unescaped forms, {{{name}}} and {{&name}}: saving a document version that contains them fails with an error asking you to use {{name}} instead. Versions saved before release 2.5.0 that still use them keep rendering (with the output sanitized), but must be changed to {{ }} the next time their contents are edited.
Variable Substitution
Simple Variables
Use basic Handlebars expressions for simple variable substitution:
Template:
<p>{{firstname}} {{lastname}}</p>
Data:
tc.setDynamicData({
firstname: 'Yehuda',
lastname: 'Katz'
});
Result:
<p>Yehuda Katz</p>
Path Expressions
For complex nested data structures, use path expressions:
Template:
<p>{{person.firstname}} {{person.lastname}}</p>
<p>Email: {{person.contact.email}}</p>
Data:
tc.setDynamicData({
person: {
firstname: 'Yehuda',
lastname: 'Katz',
contact: {
email: '[email protected]',
phone: '555-1234'
}
}
});
Result:
<p>Yehuda Katz</p>
<p>Email: [email protected]</p>
Conditional Clauses
Using the IF Helper
Use Handlebars' built-in if helper to conditionally display clauses:
Template:
<div class="terms">
{{#if author}}
<h1>{{firstName}} {{lastName}}</h1>
<p>As an author, you retain copyright to your work.</p>
{{/if}}
{{#if enterprise}}
<p>Your enterprise agreement includes priority support.</p>
{{/if}}
</div>
Data:
tc.setDynamicData({
author: true,
enterprise: false,
firstName: 'Yehuda',
lastName: 'Katz'
});
Result:
<div class="terms">
<h1>Yehuda Katz</h1>
<p>As an author, you retain copyright to your work.</p>
</div>
IF/ELSE Conditionals
Template:
{{#if isPremium}}
<p>Premium features are included in your subscription.</p>
{{else}}
<p>Upgrade to premium for additional features.</p>
{{/if}}
Data:
tc.setDynamicData({
isPremium: true
});
Iteration with EACH
Display lists of items using the each helper:
Template:
<h3>Services Included:</h3>
<ul>
{{#each services}}
<li>{{this.name}} - ${{this.price}}/month</li>
{{/each}}
</ul>
Data:
tc.setDynamicData({
services: [
{ name: 'API Access', price: 99 },
{ name: 'Priority Support', price: 49 },
{ name: 'Custom Integrations', price: 199 }
]
});
Result:
<h3>Services Included:</h3>
<ul>
<li>API Access - $99/month</li>
<li>Priority Support - $49/month</li>
<li>Custom Integrations - $199/month</li>
</ul>
Advanced Examples
User Agreement with Personalization
Template:
<div class="user-agreement">
<h2>Terms of Service for {{user.fullName}}</h2>
<p>This agreement is entered into by {{user.fullName}}
("User") located at {{user.address.street}},
{{user.address.city}}, {{user.address.state}}
{{user.address.zipCode}}.</p>
<p>User email: {{user.email}}</p>
{{#if user.isCompany}}
<p>Company: {{user.companyName}}</p>
<p>Tax ID: {{user.taxId}}</p>
{{/if}}
<h3>Service Plan</h3>
<p>Plan: {{subscription.planName}}</p>
<p>Monthly Fee: ${{subscription.monthlyFee}}</p>
{{#if subscription.hasDiscount}}
<p>Discount: {{subscription.discountPercent}}% off for
{{subscription.discountMonths}} months</p>
{{/if}}
<h3>Features</h3>
<ul>
{{#each subscription.features}}
<li>{{this}}</li>
{{/each}}
</ul>
</div>
Data:
tc.setDynamicData({
user: {
fullName: 'Sarah Johnson',
email: '[email protected]',
isCompany: true,
companyName: 'TechStart Inc.',
taxId: '12-3456789',
address: {
street: '123 Main Street',
city: 'San Francisco',
state: 'CA',
zipCode: '94102'
}
},
subscription: {
planName: 'Enterprise',
monthlyFee: 299,
hasDiscount: true,
discountPercent: 20,
discountMonths: 3,
features: [
'Unlimited API calls',
'24/7 support',
'Custom integrations',
'Dedicated account manager'
]
}
});
Jurisdiction-Specific Terms
Template:
<h3>Governing Law</h3>
{{#if jurisdiction.isEU}}
<p>This agreement is governed by the laws of the European Union
and specifically {{jurisdiction.country}}. You have additional
rights under GDPR.</p>
{{else if jurisdiction.isUS}}
<p>This agreement is governed by the laws of {{jurisdiction.state}},
United States. Disputes will be resolved in {{jurisdiction.state}} courts.</p>
{{else}}
<p>This agreement is governed by the laws of {{jurisdiction.country}}.</p>
{{/if}}
{{#if jurisdiction.requiresDataProtection}}
<h4>Data Protection</h4>
<p>We comply with {{jurisdiction.dataProtectionLaw}} requirements.</p>
{{/if}}
Data:
tc.setDynamicData({
jurisdiction: {
isEU: true,
isUS: false,
country: 'Germany',
requiresDataProtection: true,
dataProtectionLaw: 'GDPR'
}
});
Payment Terms with Calculations
Template:
<h3>Payment Terms</h3>
<p>Base Price: ${{pricing.basePrice}}</p>
<p>Users: {{pricing.userCount}} × ${{pricing.pricePerUser}} =
${{pricing.userTotal}}</p>
{{#if pricing.hasSetupFee}}
<p>One-time Setup Fee: ${{pricing.setupFee}}</p>
{{/if}}
<p><strong>Total Monthly: ${{pricing.monthlyTotal}}</strong></p>
<p><strong>Annual Total: ${{pricing.annualTotal}}</strong></p>
{{#if pricing.autoRenewal}}
<p>This subscription will automatically renew on
{{pricing.renewalDate}}.</p>
{{/if}}
Data:
tc.setDynamicData({
pricing: {
basePrice: 99,
userCount: 10,
pricePerUser: 15,
userTotal: 150,
hasSetupFee: true,
setupFee: 500,
monthlyTotal: 249,
annualTotal: 2988,
autoRenewal: true,
renewalDate: 'January 1, 2026'
}
});
Complete Integration Example
Here's a full example showing dynamic contracts in a signup flow:
import { ToughClicks, TCDisplayMethod } from '@toughclicks/js-client-sdk';
import '@toughclicks/js-client-sdk/toughclicks.css';
// User data from your application
const userData = {
firstName: 'Jane',
lastName: 'Doe',
email: '[email protected]',
company: 'Acme Corp',
plan: 'Professional',
features: ['API Access', 'Priority Support', 'Analytics Dashboard']
};
// Initialize ToughClicks
const tc = new ToughClicks(
'your-client-token',
'your-packet-id'
);
// Set dynamic data before rendering
tc.setDynamicData({
user: {
firstName: userData.firstName,
lastName: userData.lastName,
fullName: `${userData.firstName} ${userData.lastName}`,
email: userData.email,
company: userData.company
},
subscription: {
plan: userData.plan,
features: userData.features,
startDate: new Date().toLocaleDateString(),
hasCompany: !!userData.company
}
});
// Configure display
tc.setDisplayOptions({
containerId: 'tc-agreements',
signerId: userData.email,
displayMethod: TCDisplayMethod.individual,
shouldOpenModal: true
});
// Render with dynamic data
tc.render().then(() => {
console.log('Dynamic contract rendered successfully');
});
// Listen for acceptance
tc.on('tc-accepted', (event) => {
if (event.detail.allAccepted) {
console.log('User accepted personalized terms');
// Proceed with signup
}
});
React Component Example
import { useEffect, useState } from 'react';
import { ToughClicks, TCDisplayMethod } from '@toughclicks/js-client-sdk';
import '@toughclicks/js-client-sdk/toughclicks.css';
function DynamicTerms({ user, subscription }) {
const [termsAccepted, setTermsAccepted] = useState(false);
useEffect(() => {
const tc = new ToughClicks(
process.env.REACT_APP_TC_TOKEN,
process.env.REACT_APP_TC_PACKET_ID
);
// Set dynamic data based on props
tc.setDynamicData({
user: {
fullName: `${user.firstName} ${user.lastName}`,
email: user.email,
company: user.company,
address: user.address
},
subscription: {
planName: subscription.plan,
features: subscription.features,
pricing: subscription.pricing,
startDate: new Date().toLocaleDateString()
}
});
tc.setDisplayOptions({
containerId: 'dynamic-terms',
signerId: user.email,
displayMethod: TCDisplayMethod.individual,
shouldOpenModal: true
});
tc.on('tc-accepted', (e) => {
if (e.detail.allAccepted) {
setTermsAccepted(true);
}
});
tc.render();
return () => {
// Cleanup
};
}, [user, subscription]);
return (
<div>
<h2>Review Your Personalized Agreement</h2>
<div id="dynamic-terms"></div>
{termsAccepted && (
<p className="success">Thank you for accepting the terms!</p>
)}
</div>
);
}
Best Practices
1. Validate Data Before Setting
Always validate dynamic data to prevent rendering errors:
const validateDynamicData = (data) => {
if (!data.user || !data.user.email) {
throw new Error('User email is required');
}
if (!data.subscription || !data.subscription.plan) {
throw new Error('Subscription plan is required');
}
return true;
};
try {
validateDynamicData(dynamicData);
tc.setDynamicData(dynamicData);
tc.render();
} catch (error) {
console.error('Invalid dynamic data:', error);
}
2. Provide Default Values
Use default values for optional fields:
tc.setDynamicData({
user: {
name: userData.name || 'User',
company: userData.company || 'N/A',
email: userData.email
},
features: userData.features || []
});
3. Keep Data Small and Plain
HTML tags are stripped from dynamic data values for you (see Limits and Sanitization), so there is no need to escape user input yourself. Do send only the values your templates use: dynamic data is stored with every acceptance record and is limited to 60 KB.
tc.setDynamicData({
user: {
name: userInput.name, // "<b>Ada</b>" renders as "Ada"
company: userInput.company
}
});
4. Test All Variations
Test all conditional paths in your templates:
// Test with enterprise user
tc.setDynamicData({ isEnterprise: true, ... });
tc.render();
// Test with standard user
tc.setDynamicData({ isEnterprise: false, ... });
tc.render();
5. Keep Templates Readable
Make your templates maintainable:
<!-- Good: Clear structure -->
{{#if user.isPremium}}
<section class="premium-features">
<h3>Premium Features</h3>
{{#each premiumFeatures}}
<p>{{this.name}}: {{this.description}}</p>
{{/each}}
</section>
{{/if}}
<!-- Avoid: Complex nested logic -->
{{#if user.isPremium}}{{#if user.isAnnual}}{{#if user.hasDiscount}}...{{/if}}{{/if}}{{/if}}
Troubleshooting
Data Not Appearing
If variables don't render:
- Check that
setDynamicData()is called beforerender() - Verify the data structure matches your template
- Enable debug mode to see what data is being processed
tc.setDebug(true);
tc.setDynamicData(yourData);
tc.printState(); // View current state
Conditional Clauses Not Working
Ensure you're using proper Handlebars syntax:
// Correct
{{#if condition}}...{{/if}}
// Incorrect
{{if condition}}...{{/if}} // Missing #
Missing Variables
If a variable is undefined, Handlebars renders an empty string. Provide defaults:
<!-- With default -->
<p>Name: {{user.name}} {{#unless user.name}}N/A{{/unless}}</p>
<!-- Or in your data -->
tc.setDynamicData({
user: {
name: userData.name || 'N/A'
}
});
Next Steps
- Explore force reacceptance for handling document updates
- Learn about testing and debugging dynamic templates
- Configure custom data for acceptance metadata