Template API Reference
The Template API allows you to create Code Connect templates that control how your components are outputted in MCP or displayed in Figma's Code Connect panel.
This reference documents the complete API surface, from basic template structure to advanced features like property access and layer finding. If you're just getting started, we recommend first reading about template files.
figma
This is the core object that provides access to your Figma file's data. You can import it in your template file using:
import figma from 'figma'
Export Format
Templates should export an object with the following format:
export default {
example: figma.code`<code>`, // The rendered code sections
id: string, // Your custom identifier (also known as a Code Connect ID) to connect this template with a Figma instance
metadata?: {
/**
* Controls how nested components appear in the Code Connect panel:
* - true: Component code is shown directly in its parent
* Example: Small icons or labels within a button
* - false: Component appears as a pill that expands on click
* Example: Complex components like modals or forms
*/
nestable?: boolean,
/**
* Data that will be available to components that use this instance.
* See the executeTemplate() method below for details on accessing these props.
*/
props?: Record<string, any>,
}
}
The id field lets you define a custom identifier, also known as a Code Connect ID, for this template. You can use any string value you choose - this ID is how other templates will find and reference this instance using methods like findConnectedInstance(id).
The metadata field contains optional display settings:
nestable: Whentrue, shows nested component code inline with its parent; whenfalse, shows nested components as expandable pillsprops: Makes data available to parent templates throughexecuteTemplate().metadata.props
figma.selectedInstance: InstanceHandle
The selectedInstance object represents the currently selected layer in the Figma document. This provides access to various properties and methods that allow you to interact with the selected layer.
figma.code
figma.code is a tagged template literal used to build code snippets. It can be interpolated with values (strings, booleans, enums), nested code snippets, and nested lists of rendered sections.
const iconSnippet = instance.findInstance('Icon').executeTemplate().example
const labelContent = instance.findInstance('Label').executeTemplate().example
const label = figma.code`<label>${labelContent}</label>`
export default {
example: figma.code`
<Button disabled={${disabled}}>
${iconSnippet}
${label}
</Button>
`,
...
}
Important: While snippets look like template strings, they use an array structure under the hood to support clickable pills and error rendering. Do not perform string operations like concatenation on snippet values — always compose them inside figma.code:
// ✓ correct
figma.code`<MyExample />${showIcon ? iconSnippet : null}`
// ✗ incorrect — breaks rendering
'<MyExample />' + iconSnippet
figma.batch
figma.batch is available in batch template files and provides access to the per-component data defined in the corresponding .figma.batch.json file. It includes the reserved fields url, source, and component, plus any additional properties defined for that component entry.
figma.batch: {
url: string
source?: string
component?: string
[key: string]: any
}
See Batch files for full details.
figma.helpers
Note: These helpers are useful when dealing with a broad range of possible types or ways something can appear in code. Often, these can be skipped if you know exactly how some code should look.
The figma.helpers object provides utility functions for rendering template values correctly in different languages and frameworks. These helpers handle proper formatting, escaping, and rendering of complex values.
React Helpers
Available at figma.helpers.react:
renderProp(name: string, prop: any): string
Renders a React prop correctly based on its type. This helper handles all the complexity of formatting different prop types for JSX.
Examples:
// Boolean props
figma.helpers.react.renderProp('disabled', true)
// Returns: " disabled"
figma.helpers.react.renderProp('disabled', false)
// Returns: ""
// String props
figma.helpers.react.renderProp('label', 'Click me')
// Returns: ' label="Click me"'
// Number props
figma.helpers.react.renderProp('count', 42)
// Returns: " count={42}"
// Instance/component props
const icon = figma.selectedInstance.getInstanceSwap('Icon')
figma.helpers.react.renderProp('icon', icon?.executeTemplate().example)
// Returns: " icon={<Icon />}" (as sections)
renderChildren(prop: any): string | ResultSection[]
Renders React children correctly based on their type. Handles strings, numbers, booleans, instances, and special value types.
Examples:
// String children
figma.helpers.react.renderChildren('Hello')
// Returns: "Hello"
// Instance children
const children = figma.selectedInstance.findConnectedInstances(...)
figma.helpers.react.renderChildren(children.map(c => c.executeTemplate().example))
// Returns: array of ResultSections representing the children
Value Type Helpers
These helpers create typed values that renderProp and renderChildren know how to format:
jsxElement(value: string) - Wraps a value to be rendered as JSX
figma.helpers.react.jsxElement('<CustomIcon />')
// When used in renderProp: icon={<CustomIcon />}
function(value: string) - Wraps a value to be rendered as a function
figma.helpers.react.function('() => alert("clicked")')
// When used in renderProp: onClick={() => alert("clicked")}
identifier(value: string) - Wraps a value to be rendered as an identifier
figma.helpers.react.identifier('myVariable')
// When used in renderProp: value={myVariable}
object(value: Record<string, any>) - Wraps a value to be rendered as an object literal
figma.helpers.react.object({ color: 'red', size: 'large' })
// When used in renderProp: sx={{ color: "red", size: "large" }}
templateString(value: string) - Wraps a value to be rendered as a template literal
figma.helpers.react.templateString('Hello ${name}')
// When used in renderProp: message={`Hello ${name}`}
reactComponent(value: string) - Wraps a value to be rendered as a React component
figma.helpers.react.reactComponent('MyComponent')
// When used as children: <MyComponent />
array(value: any[]) - Wraps a value to be rendered as an array
figma.helpers.react.array([1, 2, 3])
// When used in renderProp: items={[1,2,3]}
renderPropValue(prop: any): string | ResultSection[]
Renders a prop value for use in object literals. Similar to renderProp but formats the value for object contexts rather than JSX attributes.
Example:
// Used internally by object literals
const styleObj = {
color: figma.selectedInstance.getString('color'),
size: figma.selectedInstance.getEnum('size', { small: 12, large: 16 })
}
// renderPropValue handles formatting these values correctly
stringifyObject(obj: any): string
Converts an object to a string representation suitable for code generation. Handles nested objects and arrays.
Example:
figma.helpers.react.stringifyObject({ a: 1, b: [2, 3], c: { d: 4 } })
// Returns: "{ a: 1, b: [2,3], c: { d: 4 } }"
isReactComponentArray(prop: any): boolean
Type guard that checks if a value is an array of React component sections (CODE, INSTANCE, or ERROR sections).
Note: This helper is primarily used internally by the rendering system but may be useful for advanced template logic.
Swift Helpers
Available at figma.helpers.swift:
renderChildren(children: ResultSectionList | string | undefined, prefix: string): ResultSection[]
Renders Swift children with proper indentation. Applies the given prefix to all non-empty lines and handles spacing between nested instances.
Example:
const children = figma.selectedInstance.findConnectedInstances(...)
.map(c => c.executeTemplate().example)
figma.swift`VStack {
${figma.helpers.swift.renderChildren(children, ' ')}
}`
// Properly indents all children with 2 spaces
Note: The indentation and spacing logic may need adjustment based on Swift formatting conventions. Review generated output to ensure it matches your project's style.
Kotlin Helpers
Available at figma.helpers.kotlin:
renderChildren(children: ResultSectionList | string | undefined, prefix: string): ResultSection[]
Renders Kotlin Compose children with proper indentation. Similar to the Swift helper but follows Kotlin/Compose formatting conventions.
Example:
const children = figma.selectedInstance.findConnectedInstances(...)
.map(c => c.executeTemplate().example)
figma.kotlin`Column {
${figma.helpers.kotlin.renderChildren(children, ' ')}
}`
// Properly indents all children with 2 spaces
Note: The indentation and spacing logic may need adjustment based on Kotlin/Compose formatting conventions. Review generated output to ensure it matches your project's style.
InstanceHandle Object
Properties
properties: Record<string, string | boolean | InstanceHandle>
- Object containing all properties of the instance.
Methods
getBoolean(propName: string, options?: Record<string, any>): boolean | any
- Gets a boolean property value.
- Optional mapping object can transform the boolean value to any other type.
getString(propName: string): string
- Gets a string property value.
getEnum(propName: string, options: Record<string, any>): any
- Gets an enum property value with optional value mapping.
- The options object maps enum values to desired output values.
getSlot(propName: string): SlotResult | undefined
- Gets a slot property value.
- Returns a
SlotResult, orundefinedif the slot property is not found or has no valid reference.
Note: To use slots, you need to install the latest version of Code Connect CLI.
getInstanceSwap(propName: string): InstanceHandle
- Gets an instance property value.
- Returns the
InstanceHandlefor the swapped instance.
getPropertyValue(propName: string): string | boolean
- Gets a raw property value.
executeTemplate(): { example: ResultSection[], metadata: Metadata }
- Renders the instance and returns both the rendered sections and metadata.
hasCodeConnect(): boolean
- Returns whether the instance has Code Connect.
codeConnectId(): string | null
- Returns the Code Connect ID of the instance, if it exists.
findText(layerName: string, opts?: SelectorOptions): TextHandle | ErrorHandle
- Finds a text layer by name.
- Optional selector options for path matching and traversal behavior.
findInstance(layerName: string, opts?: SelectorOptions): InstanceHandle | ErrorHandle
- Finds a child instance layer by name.
- Optional selector options for path matching and traversal behavior.
findConnectedInstance(codeConnectId: string, opts?: SelectorOptions): InstanceHandle | ErrorHandle
- Finds a child instance by its Code Connect ID.
- Optional selector options for path matching and traversal behavior.
findConnectedInstances(selectorFn: (node: InstanceHandle) => boolean, opts?: SelectorOptions): InstanceHandle[]
- Finds all child instances that match the selector function.
- Optional selector options for path matching and traversal behavior.
findLayers(selectorFn: (node: InstanceHandle | TextHandle) => boolean, opts?: SelectorOptions): (InstanceHandle | TextHandle | ErrorHandle)[]
- Finds all layers (instances or text) that match the selector function.
- Optional selector options for path matching and traversal behavior.
TextHandle Object
Properties
textContent: string
- The text content of the text layer.
SlotResult Object
SlotResult is the value returned by getSlot(). It can be interpolated into figma.code to render a clickable reference to the slot.
Properties
connectedInstances: InstanceHandle[]
- The code-connected component instances placed directly in the slot.
- The lookup is shallow and omits text, layers, unconnected instances, and instances nested inside another instance.
To render the connected examples inline, call executeTemplate() on each instance:
const slot = figma.selectedInstance.getSlot('Items')
const items = slot.connectedInstances.map((item) => item.executeTemplate().example)
const example = figma.code`<Menu>${items}</Menu>`