Write {{fields}} into a design, such as {{name}} and {{phone}}, then replace them with each customer's data. Each
value takes the style of its field, so a {{name}} set in bold orange is filled in bold orange.
Fill fields
const values = [
{ id: "name", value: "Maria Lopez" },
{ id: "title", value: "Owner" },
{ id: "phone", value: "(555) 010-2244" },
];
// One box
card.replaceVariables(values);
// Konva: every box the manager edits, or only the boxes you name
rt.manager.replaceVariables(values);
rt.manager.replaceVariables(values, [nameBox, phoneBox]);
// Plain canvas: every box, or only the boxes you name
rt.replaceVariables(values);
rt.replaceVariables(values, [nameBox, phoneBox]);
- A field is
{{+ itsid+}}, and matching ignores case:{{Name}}and{{NAME}}are both filled fromid: "name". - Each value replaces its field inside the field's run, so it keeps that run's font, size, color and other styles.
- Values are written exactly as given: a
$is a dollar sign. - A field must be in one style from
{{to}}. A field whose characters are styled differently part way through is not recognized. - Filling is not an undo step. It is for producing a customer's copy, not for editing.
- A value with characters the design font lacks, such as an emoji or Japanese text, loads what it needs, and
box.fontsReady()waits for it.
box.replaceVariables returns true when it filled something and false when the box had no matching field.
Fill again with other values
Filling replaces the fields with the values, so a filled box no longer has {{name}} in it. Keep the template document
and fill a fresh copy for each customer:
const template = JSON.stringify(card.getDocument()); // the design, with its fields
function showCustomer(values) {
card.setDocument(JSON.parse(template));
card.replaceVariables(values);
}
Fill a document with no box
replaceVariablesInDocument fills a document directly, for a batch job or before a design reaches a canvas. It returns a new document and never changes the one you pass. When there is nothing to fill, it returns the document you passed.
import { replaceVariablesInDocument } from "@mycreativeshop/rich-text"; // on Konva: "@mycreativeshop/rich-text/konva"
const filled = replaceVariablesInDocument(JSON.parse(template), [{ id: "name", value: "Maria Lopez" }]);
Read-only fields
A box filled from your data can be read-only: people can still select, move and resize it with the design, but a click never starts editing it.
// Konva
new RichText({ x: 28, y: 40, width: 260, document: doc, editable: false });
nameBox.setAttr("editable", false); // later
// Plain canvas
rt.addBox({ x: 28, y: 40, width: 260, document: doc, editable: false });
nameBox.attrs.editable = false; // later
In the API reference
- RichText.replaceVariables, CanvasTextBox.replaceVariables
- CanvasRichText -
replaceVariables - replaceVariablesInDocument, VariableDefinition
- RichTextConfig and CanvasBoxConfig -
editable