Dynamic Variables and Handlebars Templates
With the Conscia Digital Experience Engine, you can use Handlebars for simple string formatting, replacing tokens in the Handlebars templates with values from Context, Component responses, and elsewhere. You can implement a solution based on this recipe that applies a Handlebars template to format a personalized response from an Orchestration Component.
In the DX Engine, JavaScript expressions can use the processHandlebars()
function to apply Handlebars templates.
The processHandlebars()
function accepts two parameters:
- The first parameter to the
processHandlebars()
function contains the Handlebars template. - The second parameter to the
processHandlebars()
function contains JSON data for that Handlebars template to process.
The result of the processHandlebars()
function is the result of using Handlebars to invoke the template with the specified values.
The DX Engine compiles and caches the Handlebars template for future use, and then invokes that template using the data provided in the second parameter.
Assume that the response of the Component with the identifier "get-user-data" appears as follows:
{
"recipient": {
"name": "User Name"
},
"anniversary": "April 30"
}
The Context includes a Handlebars template under a key named messageTemplate
:
{
"messageTemplate": "<h3>Welcome, {{recipient.name}}! Your anniversary is {anniversary}.</h3>"
}
Instead of using context, you could use a Component to retrieve the Handlebars template from another system, such as retrieving an email message body template from a Content Management System.
The following expression:
processHandlebars(contextField('messageTemplate'), componentResponse('get-user-data'))
Generates the following result:
<h3>Welcome, User Name! Your anniversary is April 20.</h3>
You can use the processHandlebars()
function in Response Transformation. For example, to add a message
value containing this formatted string to the response of the get-user-data
Component, you can use an expression such the following in the Response Transform property of that Component:
_.assign(response,
{ "message": processHandlebars(contextField('messageTemplate'), response)})
This expression uses the Lodash assign function to add a key named message to the existing response of the component.
With this addition, the response of the get-user-data
component appears as follows:
{
"recipient": {
"name": "User Name"
},
"anniversary": "April 30",
"message": "<h3>Welcome, User Name! Your anniversary is April 30.</h3>"
}