Skip to content

The HtmlEditor component supports variables. This example shows how to implement mail merge with variables.

License

Notifications You must be signed in to change notification settings

DevExpress-Examples/devextreme-htmleditor-mail-merge-with-variables

Repository files navigation

HtmlEditor for DevExtreme - How to implement mail merge with variables

The HtmlEditor component supports variables. This example demonstrates how to implement mail merge with variables.

The application contains HtmlEditor and two TextBoxes. Type values in the TextBoxes to see them merged with HtmlEditor text.

HtmlEditor - Mail merge

The core implementation for mail merge can be found within the replaceVariables(value, variablesMap) utility method. The method accepts two parameters: HtmlEditor's value and an object map. These parameters are used to parse the value, then to find and replace the variables based on the map object.

const DX_VARIABLE_CLASS = 'dx-variable';
const DATA_VAR_VALUE_ATTR = 'data-var-value';

/*
value: dxHtmlEditor.value
variableMap: object = Must contain `key: value` pairs of variable content.
    {
        'FirstName': 'John',
        'LastName': 'Smith'
    }
*/
const replaceVariables = (value, variablesMap) => {
    const parser = new DOMParser();

    replaceVariables = (value, variablesMap) => {
        const doc = parser.parseFromString(value, 'text/html');
        const variables = doc.querySelectorAll(`.${DX_VARIABLE_CLASS}`);

        variables.forEach(variable => {
            const variableValue = variablesMap[variable.getAttribute(DATA_VAR_VALUE_ATTR)];
            variable.outerHTML = variableValue;
        });

        return doc.body.innerHTML.toString();
    }

    return replaceVariables(value, variablesMap);
};

Files to Review

Documentation