Back to all How-tos

Using a selector to load part of a snippet

In this case we show how to retrieve parts of a snippet. Suppose we have a single snippet with three parts. Each part contains text wrapped in a absolute div element with an ID.

The following starting template can be used to follow along the example presented in this article.

Steps

We are going to retrieve a part from this snippet dynamically based on a certain data field value. In the example provided, we can use the “State” field to retrieve the corresponding motto.

  • if the data field value is equal to ON, retrieve the part that id is ON
  • if the data field value is equal to QC, retrieve the part that id is QC
  • if the data field value is equal to NB, retrieve the part that id is NB
  • etc.

We achieve this via scripting using the selector option in loadhtml() function The steps are as below:

  1. Right click on the Snippets folder and choose New snippet > HTML file by . Rename the snippet State-mottos
  2. In the snippet, in the Source tab, copy and paste the following texts:
    <div id="ON">Serving you proudly in @City@, Ontario: Ut incepit fidelis sic permanet</div>
    <div id="QC">Serving you proudly in @City@, Québec: Je me souviens</div>
    <div id="NB">Serving you proudly in @City@, New Brunswick: Spem reduxit</div>
    <div id="NF">Serving you proudly in @City@, Newfoundland and Labrador: Quaerite primum regnum Dei</div>
    <div id="SK">Serving you proudly in @City@, Saskatchewan: Multis e gentibus vires</div>

    As you probably noticed, we wrapped each text in an absolute div element and entered an id for each div respectively ON, QC, NB, NF and SK for each matching province motto.

  3. Save the snippet and toggle back to the document
  4. Insert a new positioned box and place it to the right side of the page (above the “Ship to:” tag is good).
  5. Set the ID attribute of this box to e.g. Motto. Click the ‘ID:’ label . A new script is created in the Scripts pane and the selector is automatically set to #Motto, our box ID.
  6. Enter the following script to load the State-mottos snippet:
    var StateValue = record.fields.State;
    var Motto = loadhtml('Snippets/State-mottos.html','#'+StateValue);
    //Replace the  `@City@` placeholder with the data field **City** value
    Motto.find('@City@').text(record.fields.City);
    results.html(Motto);
  7. Click OK to save the script
  8. Switch to the preview mode (click the Preview tab) and browse through the records to see the result.

Note: You can verify the solution’s functionality by downloading these resources.

API Features used in this how-to

Leave a Reply

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