Template V2 API Reference
The Template V2 API allows you to create custom Code Connect templates that control how your components are displayed in Figma's Code Connect panel. This API is primarily used in two ways:
-
Custom Parsers: When building a parser for a language or framework not supported by default. See the Custom Parsers documentation to get started with implementing your own parser.
-
Without a Parser: When you need direct control over how specific components are rendered, without writing a full parser. Check out the Documentation for a simpler way to customize component rendering.
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 the Custom Parsers or Raw Templates guides above.
figma
This is the core object that provides access to your Figma file's data. You can import it in your template file using:
const figma = require('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.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 instance handle for 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 an 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)[]
- 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 require('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