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). This is particularly useful when you need to:
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) as well as nested code snippets, and returns the ResultSection[] type used as the example in your export.
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.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: any, 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: any, 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): ResultSection[] | undefined
- Gets a slot property value.
- Returns an array containing a slot section object, or
undefinedif the slot property is not found or has no valid reference.
Note: To use slots (open beta), 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.
Object Types
The following types are provided by the figma package and are used throughout the API. You don't need to define these yourself - they're available when you import figma from 'figma'.
Code Sections
These types define how code is represented in the Code Connect panel:
/**
* Represents a section of code that will be rendered verbatim in the Code Connect panel
*/
type CodeSection = {
type: 'CODE'
code: string
}
/**
* Represents a child instance that will be rendered either inline or as a pill
* depending on the nestable property
*/
type InstanceSection = {
type: 'INSTANCE'
/** The guid of the instance layer */
guid: string
/** The guid of the backing component */
symbolId: string
}
/**
* Represents a slot that will be rendered as a clickable label
* linking to the slot layer in the design
*/
type SlotSection = {
type: 'SLOT'
/** The guid of the slot layer */
guid: string
}
/** Represents an error that will be displayed in the Code Connect panel */
type ErrorSection = {
type: 'ERROR'
message: string
errorObject?: ResultError
}
/** The possible sections that can appear in the Code Connect panel */
type ResultSection = CodeSection | InstanceSection | SlotSection | ErrorSection
Template Results
These types define the structure of template execution results:
/** The result of executing a template, returned by executeTemplate() */
type SectionsResult = {
result: 'SUCCESS'
data: {
type: 'SECTIONS'
sections: ResultSection[]
language: string
metadata?: {
__props: Record<string, any>
[key: string]: any
}
}
}
/** The possible values that can be used in template strings */
type TemplateArgValueKind =
| string
| boolean
| TemplateStringResult
| ResultSection[]
| undefined
type TemplateStringResult = SectionsResult['data']
Metadata Interface
This interface defines how components are displayed in the Code Connect panel:
/** Metadata that can be included in template exports */
interface Metadata {
/**
* Controls how nested instances are rendered in the Code Connect panel:
* - true: The instance's code will be rendered inline within its parent
* - false: The instance will be shown as a clickable pill that expands when clicked
*
* For example:
* - Set to true for small components like icons that make sense inline
* - Set to false for complex components that should be viewed separately
*/
nestable?: boolean
/** Props which can be consumed in a parent instance */
props?: Record<string, any>
}
Selector Options Interface
This interface provides additional control over layer finding methods:
/** Options for finding layers */
interface SelectorOptions {
/** List of parent layer names that matches the layer hierarchy */
path?: string[]
/** Whether to search through nested instances */
traverseInstances?: boolean
}
Error Types
These types represent various errors that can occur during template execution:
/** Error when a property is not found */
type PropertyNotFoundErrorObject = {
type: 'PROPERTY_NOT_FOUND'
propertyName: string
}
/** Error when a child layer is not found */
type ChildLayerNotFoundErrorObject = {
type: 'CHILD_LAYER_NOT_FOUND'
layerName: string
}
/** Error when a property type doesn't match expected type */
type PropertyTypeMismatchErrorObject = {
type: 'PROPERTY_TYPE_MISMATCH'
propertyName: string
expectedType: string
}
/** Error during template execution */
type TemplateExecutionErrorObject = {
type: 'TEMPLATE_EXECUTION_ERROR'
}
/** All possible error types */
type ResultError =
| PropertyNotFoundErrorObject
| PropertyTypeMismatchErrorObject
| ChildLayerNotFoundErrorObject
| TemplateExecutionErrorObject
Legacy API
This section documents the original Template API. The API above has nicer ergonomics and is recommended for new templates.
figma.currentLayer: InstanceHandle
The currentLayer object represents the currently selected layer in the Figma document. This InstanceHandle provides access to various properties and methods that allow you to interact with the selected layer.
figma.properties
The properties object is a shorthand for figma.currentLayer.__properties__
InstanceHandle Object
Properties
children:
- List of direct children (instances or text).
__properties__
- returns a object of methods that give access to various properties on the figma node. See next section for available methods.
Methods
__find__(name): InstanceHandle | ErrorHandle | null
- Finds a child or nested child instance by name.
__findChildWithCriteria__({ type, name }: { type: 'INSTANCE' | 'TEXT'; name: string }): InstanceHandle | TextHandle | ErrorHandle | null
- Finds a child matching the specified type and name
__getPropertyValue__(name: string): string | boolean | ErrorHandle
- Gets a property value by name.
__render__(): ResultSection[]
- Returns the render information for the node.
- If an instance doesn't have an associated template then the below format is returned
{
type: 'INSTANCE' as const,
guid,
symbolId,
}
__getProps__(): Record<string, any> | ErrorHandle | undefined
- Returns the properties specified in the metadata field
__renderWithFn__(renderFn: (props: Record<string, any>) => TemplateStringResult): ResultSection[] | ErrorHandle | undefined
- Renders with a provided function.
properties or __properties__
The properties object provides several methods to interact with the properties of the current node.
boolean(propertyName: string, options?: Record<string, TemplateArgValueKind> ): boolean
This method returns the boolean value of the specified property of the layer. You can specify options to provide a mapping from a value (true/false) to anything of TemplateArgValueKind.
An example is
const booleanProperty = figma.currentLayer.__properties__.boolean("propertyName", {
"true": 'icon',
"false": undefined });
enum(propertyName: string, options: Record<string, TemplateArgValueKind> ): number
This method returns the enum value of the specified property of the layer. The keys in this options object should match the different options of that Variant in Figma, and the value is whatever you want to output instead which is of type TemplateArgValueKind.
string(propertyName: string): string
This method returns the string value of the specified property of the layer.
instance(propertyName: string): string | ResultSection[]
This method returns the rendered instance that is mapped to the instance-swap property of propertyName. This method returns the rendered instance (i.e. render() is called on it)
__instance__(instanceSwapProp: string): InstanceHandle | undefined
This method returns the instance that is mapped to the instance-swap property of propertyName. Unlike the method above, this does not call render() .
children(layerNames: string[]): ResultSection[]
This method gets any children with names in the layerNames, calls render() on them and returns this array.
Example Usage
import figma from 'figma'
const string = figma.currentLayer.__properties__.string('String Prop')
const boolean = figma.currentLayer.__properties__.boolean('Boolean Prop')
const instance = figma.currentLayer.__properties__.instance('Instance Prop')
const children = figma.currentLayer.__properties__.children(["Logic Child","Child 1","Child 2"])
export default figma.code`<Component
string={${string}}
boolean={${boolean}}
instance={${instance}}
children={${figma.code`${children}`}} />`
Using functions to encapsulate logic
To cover different types, you can include functions. Below is an example of what a complex parsed React Code Connect doc looks like.
import figma from 'figma'
function _fcc_renderProp(name, prop) {
if (Array.isArray(prop)) {
return figma.code` ${name}={<>${prop}</>}`
}
if (typeof prop === 'boolean') {
return prop ? ` ${name}` : ''
}
// Replace any newlines or quotes in the string with escaped versions
if (typeof prop === 'string') {
const str = prop.replaceAll('\n', '\\n').replaceAll('"', '\\"')
if (str === '') {
return ''
}
return ` ${name}="${str}"`
}
if (typeof prop === 'number') {
return ` ${name}={${prop}}`
}
if (prop === undefined) {
return ''
}
return ''
}
function _fcc_renderChildren(prop) {
if (Array.isArray(prop)) {
return prop
}
if (typeof prop === 'string' || typeof prop === 'number' || typeof prop === 'boolean') {
return prop
}
if (prop === undefined) {
return ''
}
}
const string = figma.currentLayer.__properties__.string('String Prop')
const boolean = figma.currentLayer.__properties__.boolean('Boolean Prop')
const instance = figma.currentLayer.__properties__.instance('Instance Prop')
const children = figma.currentLayer.__properties__.children(["Logic Child","Child 1","Child 2"])
const enumProp = figma.currentLayer.__properties__.enum('Enum Prop', {
"String": 'String',
"Number": 3,
"Boolean true": true,
"Boolean false": false,
"Undefined": undefined,
"figma.string": figma.currentLayer.__properties__.string('String Prop'),
"figma.boolean": figma.currentLayer.__properties__.boolean('Boolean Prop'),
"figma.instance": figma.currentLayer.__properties__.instance('Instance Prop'),
"figma.children": figma.currentLayer.__properties__.children(["Logic Child","Child 1","Child 2"])})
export default figma.code`<TestComponent
${_fcc_renderProp('boolean', boolean)}${_fcc_renderProp('instance', instance)}${_fcc_renderProp('childrenProp', children)}${_fcc_renderProp('enum', enumProp)}>
<div className="string">${_fcc_renderChildren(string)}</div>
<div className="boolean">${_fcc_renderChildren(boolean)}</div>
<div className="instance">${_fcc_renderChildren(instance)}</div>
<div className="children">${_fcc_renderChildren(children)}</div>
<div className="enum">${_fcc_renderChildren(enumProp)}</div>
</TestComponent>`"