Programmatic Template Updates
The updateTemplate function allows you to programmatically replace the entire template in the editor. This is useful when you need to update the template content from your application without user interaction.
Overview
Unlike the load function which is typically used during initial template loading, updateTemplate is designed for runtime updates while the editor is active. It automatically:
- Validates the template using Topol's schema validation
- Creates an undo snapshot (configurable)
- Marks the template as edited
Basic Usage
// Update template with a template object
window.TopolPlugin.updateTemplate(templateJson);
// Update template from a JSON string
window.TopolPlugin.updateTemplate(JSON.stringify(templateJson));Options
The updateTemplate function accepts an optional second parameter for configuration:
interface IUpdateTemplateOptions {
skipSnapshot?: boolean;
}| Option | Type | Default | Description |
|---|---|---|---|
skipSnapshot | boolean | false | When true, skips creating an undo snapshot before updating |
Examples
Standard Update (with Undo Support)
By default, updateTemplate creates an undo snapshot before replacing the template. This allows users to undo the programmatic change:
// User can undo this change
window.TopolPlugin.updateTemplate(newTemplate);Update Without Undo Snapshot
If you don't want the update to be undoable (e.g., when syncing with external state), use the skipSnapshot option:
// User cannot undo this change
window.TopolPlugin.updateTemplate(newTemplate, { skipSnapshot: true });Updating from External Source
A common use case is updating the template based on external events:
// Listen for external template updates
socket.on("templateUpdate", (templateData) => {
window.TopolPlugin.updateTemplate(templateData, { skipSnapshot: true });
});Template Format
Direct template object:
const template = {
tagName: "mj-global-style",
attributes: {
/* ... */
},
children: [
/* ... */
],
// ...
};
window.TopolPlugin.updateTemplate(template);Callbacks
onTemplateUpdated
Called when the template is successfully updated:
const TOPOL_OPTIONS = {
callbacks: {
onTemplateUpdated() {
console.log("Template was updated programmatically");
},
},
};onError
Called if the template update fails (e.g., invalid JSON):
const TOPOL_OPTIONS = {
callbacks: {
onError(type, message) {
if (type === "updateTemplate") {
console.error("Failed to update template:", message);
}
},
},
};Error Handling
The function validates the template before applying it. If validation fails:
- The
onErrorcallback is triggered with typeupdateTemplate - A notification is shown to the user
- The current template remains unchanged
// Handle potential errors
const TOPOL_OPTIONS = {
callbacks: {
onError(type, message) {
if (type === "updateTemplate") {
// Log error or show custom notification
console.error("Template update failed:", message);
}
},
},
};