2022.2

Table Of Contents
Example: Thescriptbelowismuchmoreefficient:itaddsthepersonalizedcontenttoastring
calledlabelStrandonlycallsafter()aftertheforloop.
var labelElm = loadhtml('snippets/label.html');
var labelStr = "";
for( var i = 0; i < record.tables.products.length); i++) {
var label = labelElm.clone();
label.find('@ProductLabel@').text(record.tables.products[i].ProductDescription);
labelStr += label;
}
results.after(labelStr);
Usereplace()
WhenpersonalizingHTMLfragmentsretrievedfromasnippetorfromthetemplateitself,JavaScript's
replace() methodshowsthebestperformance.
Replace()canonlybeusedonStrings,whilethecommandsloadhtml()andquery()returnora
QueryResult,whichisasetofstrings,liketheresultsobject.
AQueryResultallowsyoutoperformDOMmanipulationslikeaddingandremovingelements,adding
andremovingCSSclassesetc.Whentherequiredmanipulationsarelimitedtofind/replaceactions,
youcouldchangetheQueryResultintoastring.Thisallowsyoutoreplacetextusingthereplace()
method.
Forthis,youcouldusetoString():
var labelSnippet = loadhtml('snippets/label.html').toString();
OryoucouldcopytheHTMLoftheQueryResultstoavariable:
var block = results.html();var labelSnippet = loadhtml('snippets/label.html').toString();
var labelStr = "";
for( var i = 0; i < record.tables.detail.length; i++) {
var label = labelSnippet;
label = label.replace('#', i);
label = label.replace('@product@', record.tables.detail[i].fields['product']);
label = label.replace('@notes@', record.tables.detail[i].fields['notes']);
label = label.replace('@netweight@', record.tables.detail[i].fields['netweight']);
labelStr += label;
}
results.after(labelStr);
Tip: Thereplace()methodasusedintheaboveexamplereplacesonlythefirstoccurrenceof
thesearchstring.Toreplace every occurrenceofasearchstringinagivenstring,useareg-
ular expression.Inthefollowinglineofcode,theregularexpression/@product@/gmakes
replace()searchforalloccurrencesofthestring@product@inthelabelstring:
label = label.replace(/@product@/g, record.tables.detail[i].fields
['product']);
Page 382