Template API

Create, query, and manage templates. Add form elements, link industries, and control access rights for your reusable estimation templates.

Overview

Core Concept

The Template object provides factory methods for creating and querying templates. Templates are reusable estimation forms with configurable elements (text fields, numeric inputs, checkboxes, etc.) and scripted logic that generates line items automatically.

Context Variable: When a user is editing a template, the template variable is automatically available in your script. It provides access to all form elements and their current values. Use the Template factory to create new templates or query existing ones.

Template.get(id)

Method

Retrieves a template by its ID. Returns the template object or null if not found, not accessible, or not a template.

Parameters

ParameterTypeRequiredDescription
id number Yes The template ID

Returns

A Template object, or null if not found.

Examples

// Get a template by ID
var tpl = Template.get(12345);
if (tpl) {
  console.log(tpl.name);
  console.log(tpl.accessRight);
}

Template.create()

Method

Creates a new empty template.

Returns

A new Template object with all properties writable.

Example

var tpl = Template.create();
tpl.name = "Bathroom Remodel Calculator";
tpl.accessRight = "team";
tpl.save();
Navigate.to('template/' + tpl.id);

where() / findWhere()

Methods

Template.where(criteria)

Finds all templates matching the specified criteria. Returns an array.

CriteriaTypeDescription
idnumberMatch by exact template ID
namestringMatch by template name (partial match)

Example

var templates = Template.where({ name: 'Kitchen' });
console.log('Found ' + templates.length + ' kitchen templates');

for (var i = 0; i < templates.length; i++) {
  console.log(templates[i].name + ' (ID: ' + templates[i].id + ')');
}

Template.findWhere(criteria)

Finds the first template matching the criteria. Returns a single template or null.

Example

var tpl = Template.findWhere({ id: 456 });
if (tpl) {
  console.log('Found: ' + tpl.name);
  console.log('Access: ' + tpl.accessRight);
}
See also: For full details on search criteria and combining fields, see Search Patterns.

Template Properties

Reference

Template objects have the following properties:

PropertyTypeAccessDescription
id number read Unique template ID
name string read/write Template display name
typeId string read Always "template"
accessRight string read/write Access level: "user", "team", or "public"
children Collection read Form elements collection (text, numeric, checkbox, etc.)
items Collection read Line items collection (Item and VirtualItem elements only)
industries Collection read Linked industries. See Industries Collection.

Access Rights

ValueDescription
"user" Private - only you can see and use this template (same as "private")
"team" Team - all team members can see and use this template
"public" Public - visible to everyone (requires special permissions)

save() / delete()

template.save() saves all changes to disk. template.delete() permanently removes the template.

Example

template.name = "Updated Template Name";
template.accessRight = "team";
template.save();

// Or delete
var old = Template.findWhere({ name: "Obsolete Template" });
if (old) old.delete();

Accessing Form Elements by Name

Template form elements can be accessed directly by their propName. This is the most common way to read user input in onChange scripts.

Example

// Access elements by propName
var length = template.roomLength.value;    // numeric element
var width = template.roomWidth.value;      // numeric element
var premium = template.premiumFinish.value; // checkbox element
var material = template.materialType.value; // single choice element

var area = length * width;
var rate = premium ? 12.00 : 8.50;

template.items.clear();
template.items.push({
  name: material + " Flooring",
  unitQuantity: area,
  unitCategory: 'area',
  unit: 'ft2',
  price: rate
});

Industries Collection

Reference

The template.industries property provides a collection for managing which industries this template is linked to. Industries help users find relevant templates in the marketplace.

Properties

PropertyTypeDescription
length number Number of linked industries
[index] object Access industry by index. Returns {id, name}.

template.industries.push(industry)

Links an industry to the template. Accepts an ID (number), a name (string), or an object.

ParameterTypeDescription
industrynumberIndustry ID
industrystringIndustry name (exact match)
industryobject{id: number} or {name: string}

Examples

// Add by ID
template.industries.push(5);

// Add by name
template.industries.push("Plumbing");

// Add by object
template.industries.push({ id: 12 });
template.industries.push({ name: "Electrical" });

template.industries.remove(identifier)

Removes an industry from the template. Returns true if removed.

ParameterTypeDescription
identifiernumberIndustry ID or array index
identifierstringIndustry name

Examples

// Remove by name
template.industries.remove("Plumbing");

// Remove by ID
template.industries.remove(5);

// Remove by index
template.industries.remove(0);

template.industries.toArray()

Returns all linked industries as an array of {id, name} objects.

Example

var industries = template.industries.toArray();
for (var i = 0; i < industries.length; i++) {
  console.log(industries[i].id + ': ' + industries[i].name);
}
Related: Use Industries.list() or Industries.search() to browse available industries. See Industries API.

Template Files

Scripting

A template's script can be split into named JavaScript files - lib/pricing.js, lib/geometry.js - that it imports. The template's script is still what runs when a value changes; the files are the code it imports. Large templates stay readable, and a helper is written once instead of being pasted into every script.

Managing files: files are created, read and changed with the MCP template file tools (template_file_set, template_file_edit, template_file_get, ... - see MCP API Integration). A change takes effect on the next run.

Importing a File

// lib/area.js - a template file
export function area(length, width) {
  return length * width;
}

export const WASTE = 1.10;
// The template's script
import { area, WASTE } from './lib/area.js';

var sqft = area(template.roomLength.value || 0, template.roomWidth.value || 0);
template.items.clear();
if (sqft > 0) {
  template.items.push({
    name: "Flooring",
    unitQuantity: sqft * WASTE,
    unitCategory: 'area',
    unit: 'ft2',
    price: 6.00
  });
}

A file sees the same globals as the script (template, document, console, the SDK objects), so a helper can read form values or push items itself. A file imported several times runs once.

GetCost Library

GetCost publishes ready-made files every template can import - no setup, no copy. An import that is not one of the template's own files is looked up in the library, under lib/gc/. A template's own file with the same path always wins. The library is updated in place: a template always gets its latest version.

import { rectArea, roofArea } from './lib/gc/geometry.js';
import { withWaste, packages } from './lib/gc/quantities.js';

var plan = rectArea(template.length.value, template.width.value);
var roof = roofArea(plan, template.pitch.value);            // 6/12 pitch: x 1.118
template.boxes.value = packages(withWaste(roof, 10), 33.3); // 10% waste, 33.3 sq ft per bundle
FileExports
lib/gc/units.jsftToM, mToFt, inToCm, cmToIn, inToFt, ftToIn, feetInches(ft, in), sqftToM2, m2ToSqft, cuftToCuyd, cuydToCuft, cuydToM3, m3ToCuyd, galToL, lToGal
lib/gc/geometry.jsrectArea, rectPerimeter, triangleArea, circleArea(diameter), circleCircumference, gableArea(width, rise), wallArea(length, width, height), netWallArea(gross, openings), boxVolume, cylinderVolume, roofPitchFactor(risePer12), roofArea(planArea, risePer12), rafterLength(run, risePer12)
lib/gc/quantities.jswithWaste(qty, percent), packages(qty, perPackage), sheets(area, w = 4, l = 8), studs(lengthFt, spacingIn = 16), pieces(total, pieceLength), paintGallons(area, coats, coverage = 350), roundTo(value, increment), ceil
lib/gc/format.jsnumber(value, decimals = 2), feetInchesLabel(decimalFeet) (10' 6"), dimensions(l, w, unit), plural(count, one, many)

A script that only imports the library needs no files of its own. Sizes that are missing or negative count as 0.

Rules

RuleDetails
Imports start with ./Relative to the importing file's folder: from the script, ./lib/area.js; from lib/calc.js, ./area.js is lib/area.js. ../, /x.js, bare names (lodash) and URLs are refused.
Only this template's files, then the GetCost libraryAn import resolves inside the form's own files, then the GetCost library - never another business's template, never the web.
Imports are .jsPaths use letters, digits, ., _, - per folder; at most 255 characters; 1 MB per file. A template can also store .css and .html files, but they cannot be imported.
SDK 3.0 or laterA template with files runs on the JavaScript SDK (version 3.0+), not Lua.
Module rulesWith files, the script runs as a module: strict mode (declare every variable), and no return at the top level - wrap early exits in an if or a function.
A refused import ends the runIt cannot be caught with try/catch; the run reports which import, and from which file.

Versions

Every change to a file saves a new version; old versions are never changed or removed (template_file_history lists them, template_file_diff compares two). A document keeps the versions it was created with: changing a template's file changes the template and the documents made from it afterwards - never an estimate already made. A file changed inside a document belongs to that document; the template is not touched.

Who Runs Them

Files load for the template's own runs - typing in its form, its actions. A script run by an AI assistant or run_script sees the template as a global but does not load its files. A run is refused, before any code runs, when:

MessageWhy
Template files need SDK version 3.0 or later.The form still runs a Lua (pre-3.0) script.
This template's files are not available to you.A file belongs to a template you may not use (another business's private template).
This template's files could not be loaded right now. Please try again.A temporary problem reading the files.

Keeping Code Private

The form's script is part of the template's design, so anyone who opens the template receives it - including visitors of a public template. A template's files are not: their code runs on GetCost's servers and is never sent to the browser, and only your team can read it (the MCP file tools refuse everyone else, even on a public template). To protect your work, keep the form's script to a few lines and put the real code in files.

Practical Examples

Code Examples

Create a Template with Industries

var tpl = Template.create();
tpl.name = "Deck Construction Calculator";
tpl.accessRight = "public";

// Link to relevant industries
tpl.industries.push("Carpentry");
tpl.industries.push("General Contractor");

tpl.save();
console.log('Created template: ' + tpl.name);
console.log('Industries: ' + tpl.industries.length);

Template onChange Script (Flooring Calculator)

// This script runs when any form element changes
var length = template.roomLength.value || 0;
var width = template.roomWidth.value || 0;
var area = length * width;

if (area <= 0) {
  console.warn("Enter room dimensions to calculate");
  return;
}

// Clear previous items and recalculate
template.items.clear();

// Material
var materialChoice = template.materialType.value;
var pricePerSqFt = materialChoice === "hardwood" ? 8.50 :
                   materialChoice === "laminate" ? 4.00 : 6.00;

template.items.push({
  name: materialChoice + " Flooring",
  unitQuantity: area,
  unitCategory: 'area',
  unit: 'ft2',
  price: pricePerSqFt
});

// Underlayment (10% waste factor)
template.items.push({
  name: "Underlayment",
  unitQuantity: area * 1.10,
  unitCategory: 'area',
  unit: 'ft2',
  price: 0.75
});

// Labor
var laborHours = area / 50; // 50 sq ft per hour
template.items.push({
  name: "Installation Labor",
  unitQuantity: laborHours,
  unitCategory: 'time',
  unit: 'h',
  price: 65.00
});

Share a Template with Your Team

var tpl = Template.findWhere({ name: "Kitchen Estimate" });
if (tpl) {
  tpl.accessRight = "team";
  tpl.save();
  console.log("Template shared with team");
} else {
  console.error("Template not found");
}