Back to all How-tos

Load a snippet based on a data field value

In this How-To, we will personalize a letter for each customer using snippets, based on a value in a data field. This functionality is often used to add customer specific elements.

Our snippets contain the text for a letter to customers who practice a particular sport: volleyball, hockey or basketball. We set the letter’s text dynamically based on a value stored in the data field “Preference”. So, we created snippets that contain a text depending on the preference. The contents of these snippets can be retrieved with a script.

You can find the resources for this example in this file: Howto_Load-Snippet.

Quick Steps

  1. Create a new Print template.
  2. Drag the three Letter-… .HTML files from the resources to the Snippets folder located in the Resources pane. (You can view a snippet’s content by double-clicking on it.)
  3. Open the data mapping configuration from the resources.
  4. Open the Print section Section 1 by double-clicking on it.
  5. Add a placeholder text to the paragraph, e.g. [letter text].
  6. On the Attributes Pane, give the paragraph an ID, e.g. contents.
  7. Right-click on the paragraph and select New script… The script editor opens and you will see that the paragraph’s ID is used as Selector.
  8. Type in a name for the script such as Letter Snippet and add in the following script contents:
    // Assign the data field value to a variable e.g. pref
    var pref = record.fields.Preference;
    // Load a snippet based on the value of the variable
    results.loadhtml('Snippets/Letter-'+pref+'.html');
    
  9. Click OK to save the script.
  10. Switch to Preview mode to view the result

Note: The text of the letter contains a placeholder, e.g. @FirstName@, which is to be replaced with a value by a text script. To make this happen, we either have to:

  • Order the scripts in the Scripts pane and make sure that a text script that replaces @firstname@ comes after the script that loads the snippet.
  • Replace the placeholder via the script that loads the snippet. The following line of code loads the snippet and replaces the @FirstName@ placeholder with the value of a data field:
    results.loadhtml('Snippets/Letter-'+pref+'.html').find('@FirstName@').text(record.fields.firstname);

API features used in the script

Leave a Reply

Your email address will not be published. Required fields are marked *