Context

Build a component with a context element so that specific values are inherited across your email.

Components enable you to reuse content across emails and cascade changes to every instance when you update the original component file. Context takes this one step further. With context elements, you can define multiple versions of your component and render the desired version from email to email. If you nested components within your component, the context will cascade down.

A context is set using the <context> element. This requires name and value attributes. You can then reference the value by calling the name in the component.

<component>
<context name="users" value="{name:'World'}">
<p>Hello ${context.users.name}</p>
</context>
</component>

The name attribute must start with a letter and can only contain letters or numbers. It cannot have any symbols or spaces.

The value attribute can contain a number of values, such as a boolean (true/false) value or a string. It can also contain a JavaScript object.

Render Context Based on Different Values

Now, imagine you manage multiple brands across your emails. You could create a component with a context for all your brands then reference the brand you want for each email.

<meta name="label" content="my-component" />
<fieldset>
<input type="radio" name="brand" value="parcel" checked>
<input type="radio" name="brand" value="customerio">
</fieldset>
<component>
<context name="styles" value="{
brand: ({
parcel: {
name: 'parcel',
text: '#fcfdff',
background: '#0d1117',
link: '#198cff'
},
customerio: {
name: 'customer.io',
text: '#343446',
background: '#ffffff',
link: '#5721cc'
}
})[brand]
}">
<div set:style="`background-color:${context.styles.brand.background};color:${context.styles.brand.text};`">
<p>This is the branding for ${context.styles.brand.name}</p>
</div>
</context>
</component>

In the fieldset, there is a brand property that has 2 values parcel and customerio. In the component, there is a <context> element with a name of styles and a value set to an array. The array is called brand and contains brand styles for both parcel and customerio. At the end of the array, we’ve set [brand] to tie in the value set in our component's properties to the context.

Now, we can reference <my-component brand="customerio"></my-component> or <my-component brand="parcel"></my-component> in an email and the component's content will render based on the brand specified.

Nest Components to Inherit Context

You can nest components within one another so they inherit your context, too. This makes it possible for you to build an entire email from reusable components and change how it renders based on a single line of HTML.

<my-component brand="parcel">
<component-2></component-2>
<component-3>
<component-a></component-a>
</component-3>
</my-component>

Each nested component would inherit the brand context of <my-component>.