Add custom values as the data sources to a template

We can pass custom objects, and XML values as data sources to a template instead of a single record data.
Use the function TemplateRenderer.addCustomDataSource(options) for this. This is a part of the N/render module and is available for all server scripts(of the 2.x version).
The parameters require are:

  1. ‘options.alias’ of string type which stores alias for the data source
  2. ‘options.format’ can be any of the values: JSON, OBJECT, XML_DOC, XML_STRING describing data type
  3. ‘options.data’ is the data value and can be an Object, Document, or string
    This is particularly helpful when the value is not stored in a single record and needs to be fetched from some other source. Refer to the code for more:

//Add additional code

var renderer = render.create();

var xmlObj = xml.Parser.fromString(xmlString);
var jsonObj = JSON.parse(jsonString);

renderer.templateContent = “${XML.book.title}
${XML.book.chapter[1].title}
${JSON.book.title}
${JSON.book.chapter[1].title}
${JSON_STR.book.title}
${XML_STR.book.title}”;

renderer.addCustomDataSource({
format: render.DataSource.XML_DOC,
alias: “XML”,
data: xmlObj
});
renderer.addCustomDataSource({
format: render.DataSource.XML_STRING,
alias: “XML_STR”,
data: xmlString
});
renderer.addCustomDataSource({
format: render.DataSource.OBJECT,
alias: “JSON”,
data: jsonObj
});
renderer.addCustomDataSource({
format: render.DataSource.JSON,
alias: “JSON_STR”,
data: jsonString
});

var xml = renderer.renderAsString();

//Add additional code

Leave a comment

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