Template functions
Home Assistant extends the Jinja2 template engine with many custom functions, filters, and tests. Each one has its own page with detailed descriptions, parameters, and practical examples.
New to templates? Start with the templating documentation to learn the basics.
Areas
-
Get devices in an area
area_devicesReturns a list of device IDs associated with a given area. -
Get entities in an area
area_entitiesReturns a list of entity IDs associated with a given area. -
Get area ID
area_idReturns the area ID for a given area name, entity ID, or device ID. -
Get area name
area_nameReturns the friendly name of an area from its ID, entity ID, or device ID. -
Get all
areasReturns a list of all area IDs in your Home Assistant instance.
Collections
-
Get object ibute
attrReads an attribute from an object when the attribute name comes from a variable. -
Split list into es
batchSplits a list into smaller batches of a specified size. -
Merge dictionaries
combineMerges multiple dictionaries into one. -
Sort a dictionary
dictsortSorts a dictionary by its keys or values, returning a list of key/value pairs. -
Set
differenceReturns items in the first list but not in the second (set difference). -
Get item
firstReturns the first item of a list or the first character of a string. -
Flatten nested lists
flattenFlattens nested lists into a single flat list. -
Parse JSON string
from_jsonParses a JSON string into a Python object. -
Group items by attribute
groupbyGroups a list of items by a common attribute, producing a list of (grouper, list) pairs. -
Set ion
intersectReturns items common to both lists (set intersection). -
Get dictionary key/value pairs
itemsReturns the key/value pairs from a dictionary as a list of tuples. -
Get item
lastReturns the last item of a list or the last character of a string. -
Get of a collection
lengthReturns the number of items in a list, characters in a string, or keys in a dictionary. Also available as count. -
Transform list items
mapApplies a filter to each item or extracts an attribute from each item in a list. -
Merge action responses
merge_responseMerges action response dictionaries into a flat list. -
Remove items by test
rejectFilters a list, removing items that pass a given test. The opposite of select. -
Remove items by attribute test
rejectattrFilters a list, removing items where a specified attribute passes a test. The opposite of selectattr. -
Reverse a list or string
reverseReverses the order of items in a list or characters in a string. -
Filter items by test
selectFilters a list, keeping only items that pass a given test. -
Filter items by attribute test
selectattrFilters a list, keeping only items where a specified attribute passes a test. -
Convert to
setConverts an iterable to a set, removing duplicate values. -
Randomly a list
shuffleRandomly shuffles the items in a list. -
Slice a list into sub-lists
sliceSlices a list into a specified number of sub-lists of roughly equal size. -
Sort a list
sortSorts the items in a list, with optional attribute-based and reverse sorting. -
Sum values in a list
sumSums all values in a list, with optional attribute extraction and start value. -
Set symmetric difference
symmetric_differenceReturns items in either list but not in both. -
Serialize to JSON
to_jsonSerializes a value to a JSON string. -
Convert to
tupleConverts an iterable to a tuple. -
Set
unionReturns all unique items from both lists (set union). -
Remove duplicate values
uniqueRemoves duplicate values from a list, keeping only unique items.
Comparison
-
Test uality
eqTests if two values are equal. Also known as equalto or ==. -
Test greater than or equal
geTests if a value is greater than or equal to another. Also known as >=. -
Test greater than
gtTests if a value is greater than another. Also known as greaterthan or >. -
Test ss than or equal
leTests if a value is less than or equal to another. Also known as <=. -
Test less than
ltTests if a value is less than another. Also known as lessthan or <. -
Test not equal
neTests if two values are not equal. Also known as !=.
Date & Time
-
Convert to datetime
as_datetimeConverts a string or timestamp to a datetime object. -
Convert to local time zone
as_localConverts a datetime object to your local time zone. -
Parse duration string
as_timedeltaParses an ISO 8601 duration string into a timedelta object. -
Convert to UNIX timestamp
as_timestampConverts a datetime object or string to a UNIX timestamp. -
Current local date and time
nowReturns the current date and time in your local time zone. -
Relative time (deprecated)
relative_timeReturns a human-readable string describing how long ago a datetime was. -
Parse a time string
strptimeParses a time string with a specified format into a datetime object. -
Human-readable time elapsed
time_sinceReturns a human-readable string describing how much time has passed since a datetime. -
Human-readable time remaining
time_untilReturns a human-readable string describing how much time remains until a datetime. -
Create a time duration
timedeltaCreates a timedelta object from numeric time components. -
Format timestamp with custom format
timestamp_customFormats a UNIX timestamp as a string using a custom format. -
Format timestamp as local time
timestamp_localFormats a UNIX timestamp as a local datetime string. -
Format timestamp as UTC time
timestamp_utcFormats a UNIX timestamp as a UTC datetime string. -
Today at a specific time
today_atReturns today's date combined with a specific time. -
Current UTC date and time
utcnowReturns the current date and time in UTC.
Devices
-
Get device attribute
device_attrReturns the value of a specific attribute from a device. -
Get entities for a device
device_entitiesReturns a list of entity IDs associated with a given device. -
Get a device ID
device_idReturns the device ID for a given entity ID or device name. -
Get a device name
device_nameReturns the name of a device from a device ID or entity ID. -
Test device attribute
is_device_attrTests if a specific attribute of a device has a given value.
Encoding
-
Decode from base64
base64_decodeDecodes a base64-encoded string. -
Encode to base64
base64_encodeEncodes a string or bytes to a base64 string. -
Decode hex string to bytes
from_hexDecodes a hexadecimal string into bytes. -
MD5 hash
md5Calculates the MD5 hash of a string. -
Pack value to bytes
packPacks a value into bytes using a Python struct format string. -
SHA1 hash
sha1Calculates the SHA1 hash of a string. -
SHA256 hash
sha256Calculates the SHA256 hash of a string. -
SHA512 hash
sha512Calculates the SHA512 hash of a string. -
Unpack bytes to value
unpackUnpacks bytes into a value using a Python struct format string.
Entities
-
Get config entry attribute
config_entry_attrGets a specific attribute from a config entry. -
Get config entry ID
config_entry_idGets the config entry ID from an entity ID. -
Get entity name
entity_nameGets the friendly name of an entity from its entity ID. -
Get entities for an integration
integration_entitiesReturns a list of entity IDs tied to an integration or config entry. -
Test if entity is hidden
is_hidden_entityTests if an entity is hidden in the entity registry.
Floors
-
Get areas on a floor
floor_areasReturns a list of area IDs that belong to a given floor. -
Get entities on a floor
floor_entitiesReturns a list of entity IDs for all entities on a given floor. -
Get floor ID
floor_idReturns the floor ID for a given floor name, area name, device ID, or entity ID. -
Get floor name
floor_nameReturns the friendly name of a floor from its ID, area name, device ID, or entity ID. -
Get all
floorsReturns a list of all floor IDs in your Home Assistant instance.
Functional
-
Call a function dynamically
applyCalls a function with a value, letting you pass any function into places where a filter is expected. -
Turn a macro into a function
as_functionTurns a template macro into a reusable function you can pass to map, select, and reject. -
Check if value another
containsTests if a value contains another value. Works with strings, lists, and dictionaries. -
Cycle through values
cyclerCreates an object that cycles through a list of values. Useful for alternating between values in a loop. -
Create a ionary
dictCreates a dictionary from keyword arguments. -
Immediate if (ternary)
iifShorthand for basic if/else logic in a single expression. -
Join loop iterations
joinerCreates a helper that joins loop iterations with a separator, returning an empty string on the first call. -
Generate placeholder text
lipsumGenerates lorem ipsum placeholder text. Useful for testing and prototyping templates. -
Create a mutable
namespaceCreates a mutable namespace object for storing variables across loop scopes in templates. -
Unicode code point
ordReturns the Unicode code point for a single character. -
Choose a value
randomChooses a random value from a list. Returns a different value each time the template is evaluated. -
Generate a number sequence
rangeGenerates a sequence of numbers, like Python's range(). Commonly used for looping a specific number of times. -
Parse a string
versionConverts a string into a version object that supports comparison operators. -
Combine iterables
zipZips multiple iterables together into a list of tuples, pairing elements by position.
Labels
-
Get areas with a label
label_areasReturns a list of area IDs that have a specific label assigned. -
Get label description
label_descriptionReturns the description of a label from its ID. -
Get devices with a label
label_devicesReturns a list of device IDs that have a specific label assigned. -
Get entities with a label
label_entitiesReturns a list of entity IDs that have a specific label assigned. -
Get label ID
label_idReturns the label ID for a given label name. -
Get label name
label_nameReturns the friendly name of a label from its ID. -
Get all
labelsReturns a list of all label IDs, or the labels assigned to a specific entity, device, or area.
Math
-
Absolute value
absReturns the absolute value of a number. -
Arc cosine (inverse cosine)
acosReturns the arc cosine (inverse cosine) of a value, in radians. -
Arc sine (inverse sine)
asinReturns the arc sine (inverse sine) of a value, in radians. -
Arc tangent (inverse tangent)
atanReturns the arc tangent (inverse tangent) of a value, in radians. -
Four-quadrant arc tangent
atan2Returns the four-quadrant arc tangent of y/x, in radians. -
Average (arithmetic mean)
averageCalculates the arithmetic mean of a list of values. -
Bitwise AND
bitwise_andPerforms a bitwise AND operation on two values. -
Bitwise OR
bitwise_orPerforms a bitwise OR operation on two values. -
Bitwise XOR
bitwise_xorPerforms a bitwise XOR (exclusive OR) operation on two values. -
Clamp (constrain) a value
clampConstrains a value between a minimum and maximum bound. -
Cosine
cosReturns the cosine of a value given in radians. -
Test if divisible by
divisiblebyTests whether a number is divisible by another number. -
Eulr's numbr
eThe mathematical constant e (Euler's number), approximately 2.71828. -
Test if
evenTests whether a number is even. -
Logarithm
logReturns the logarithm of a value with an optional base (default is natural logarithm). -
Maximum value
maxReturns the largest value from a list of values. -
Statistical
medianCalculates the statistical median (middle value) of a list of values. -
Minimum value
minReturns the smallest value from a list of values. -
Test if
oddTests whether a number is odd. -
Pi
piThe mathematical constant pi, approximately 3.14159. -
Remap a value between ranges
remapRemaps a value from one numeric range to another, with optional stepping and edge handling. -
Sine
sinReturns the sine of a value given in radians. -
Square root
sqrtReturns the square root of a value. -
Statistical mode
statistical_modeReturns the most commonly occurring value in a list of values. -
Tangent
tanReturns the tangent of a value given in radians. -
Tau
tauThe mathematical constant tau (2 * pi), approximately 6.28318. -
Wrap a value cyclically
wrapWraps a value cyclically within a range.
Regex
-
Test if string es pattern
matchTemplate test that checks if a string matches a regular expression at the beginning. -
Find all regex matches
regex_findallFinds all occurrences of a regular expression pattern in a string and returns them as a list. -
Find regex match at index
regex_findall_indexFinds all occurrences of a regex pattern and returns the match at a specific index. -
Match a regex pattern
regex_matchTests if a string matches a regular expression pattern at the beginning. -
Replace using a regex pattern
regex_replaceReplaces all occurrences of a regular expression pattern in a string. -
Search for a regex pattern
regex_searchSearches for a regular expression pattern anywhere in a string. -
Test if string contains pattern
searchTemplate test that checks if a string contains a regular expression pattern anywhere.
Repairs
-
Get a specific repair
issueReturns a specific repair issue by domain and issue ID, or None if it does not exist. -
Get all repair
issuesReturns all active repair issues currently open in Home Assistant.
States
-
Find entity
closestFinds the entity closest to a given location, home, or another entity. -
Calculate
distanceCalculates the distance in kilometers between two points or from home. -
Expand groups into entities
expandExpands groups and zones into a sorted list of individual entity state objects. -
Check if entity has a value
has_valueTests if an entity exists and has a valid state (not unavailable or unknown). -
Test entity state
is_stateTests if an entity is in a specific state. -
Test state attribute
is_state_attrTests if a specific attribute of an entity has a given value. -
Get state attribute
state_attrReturns the value of a specific attribute from an entity's state. -
Get translated attribute value
state_attr_translatedReturns the translated value of a specific attribute from an entity's state. -
Get translated state
state_translatedReturns the translated state value of an entity in your configured language. -
Get entity state
statesReturns the state value of an entity, or lets you iterate over all entity states.
Strings
-
Capitalize first character
capitalizeCapitalizes the first character of a string and lowercases the rest. -
Center text in a field
centerCenters a string in a field of a given width, padding with spaces. -
Escape HTML characters
escapeEscapes HTML special characters in a string so they display as literal text. -
Format byte size as human-readable
filesizeformatFormats a byte count as a human-readable file size string like 1.2 MB. -
Force-escape HTML characters
forceescapeEscapes HTML special characters, even on strings already marked as safe. -
Printf-style string ting
formatFormats a string using printf-style placeholders like %s, %d, and %f. -
Indent text
indentIndents text by a given number of spaces, with options for the first line and blank lines. -
Join a list into a string
joinJoins a list of values into a single string with a separator between each element. -
Convert to case
lowerConverts all characters in a string to lowercase. -
Convert number to
ordinalConverts a number to its ordinal string representation (1st, 2nd, 3rd, and so on). -
Pretty-print a value
pprintPretty-prints a value in a readable format, useful for debugging templates. -
Replace occurrences in a string
replaceReplaces all occurrences of a substring with another string. -
Mark as HTML
safeMarks a string as safe HTML so it will not be escaped when rendered. -
Convert to slug format
slugifyConverts a string to a slug format with an optional separator character. -
Strip HTML tags
striptagsRemoves all HTML/XML tags from a string, leaving only the text content. -
Convert to case
titleConverts a string to title case, capitalizing the first letter of each word. -
Strip whitespace
trimStrips leading and trailing whitespace (or specified characters) from a string. -
Truncate text to a length
truncateTruncates a string to a given length, appending an ellipsis if it was shortened. -
Convert to case
upperConverts all characters in a string to uppercase. -
URL-encode a value
urlencodeURL-encodes a dictionary of values for use in HTTP requests. -
Convert URLs to HTML links
urlizeConverts plain text URLs into HTML links. -
Count words in text
wordcountCounts the number of words in a string. -
Wrap text at a line width
wordwrapWraps text at a given line width by inserting line breaks. -
Convert dictionary to HTML attributes
xmlattrConverts a dictionary into an XML/HTML attribute string.
Type Conversion
-
Add to a value
addAdds a specified amount to a numeric value, with an optional default if conversion fails. -
Convert to ean
boolConverts a value to a boolean (true/false), with an optional default if conversion fails. -
Test if
booleanTests whether a value is a boolean type. -
Test if
callableTests whether a value is callable (a function or method). -
Set a value
defaultProvides a default value if a variable is undefined or none. -
Test if
definedTests whether a variable is defined (not undefined). -
Test if
falseTests whether a value is false. -
Convert to
floatConverts a value to a floating-point number, with an optional default if conversion fails. -
Test if
floatTests whether a value is a floating-point number type. -
Test if sequence
inTests whether a value is contained in a sequence. -
Convert to eger
intConverts a value to an integer, with an optional default if conversion fails. -
Test if
integerTests whether a value is an integer type. -
Require a value is defined
is_definedForces a template error if the value is undefined, ensuring variables exist before use. -
Test if value is numeric
is_numberTests whether a value can be converted to a finite number. -
Test if
iterableTests whether a value is iterable. -
Convert to
listConverts a value to a list. -
Test if
mappingTests whether a value is a mapping (dictionary). -
Multiply a value
multiplyMultiplies a numeric value by a specified amount, with an optional default if conversion fails. -
Test if
noneTests whether a value is None. -
Test if
numberTests whether a value is a number (integer or float). -
Round a number
roundRounds a numeric value to a specified number of decimal places using various rounding methods. -
Test same object
sameasTests whether a value is the same object as another (identity check). -
Test if
sequenceTests whether a value is a sequence (list, tuple, or string). -
Convert to
stringConverts a value to its string representation. -
Test if
stringTests whether a value is a string type. -
Serialize to JSON
tojsonSerializes a value to a JSON-formatted string. -
Test if
trueTests whether a value is true. -
Get the type of a value
typeofReturns the type name of a value as a string. -
Test if
undefinedTests whether a variable is undefined.