Create a mutable namespace: namespace
When you try to count something inside a for loop or track a running total, you quickly hit a wall: variables changed inside the loop do not survive outside of it. The namespace template function solves this. It creates a special object whose attributes you can modify from any scope, so your counter, total, or tracker keeps its value after the loop ends.
This is one of the most important functions to understand when writing Home Assistant templates that involve loops. Without namespace, you cannot accumulate a total, track a maximum, or build a result inside a for loop and use it afterward. You create a namespace with initial values like namespace(count=0, total=0), then modify its attributes with {% set ns.count = ns.count + 1 %} inside the loop. The changes persist after the loop ends.
Usage
Here’s how to use this template function. Copy any example and adjust it to your setup.
{% set ns = namespace(counter=0) %}
{% for i in range(3) %}
{% set ns.counter = ns.counter + 1 %}
{% endfor %}
{{ ns.counter }}
3
Function signature
The signature is a technical summary of this template function. It shows the name of the function, the values (called parameters) it accepts, and what type of data each parameter expects (for example, a piece of text or a number).
Function parameters that have a = with a value after them are optional. If you leave them out, the default value shown is used automatically. Function parameters without a default are required.
namespace(
**kwargs: Any,
) -> Namespace
Function parameters
The following parameters can be provided to this function.
Why namespace is needed
Without a namespace, variables set inside a loop do not persist outside the loop. This is a common source of confusion.
{# This does NOT work as expected #}
{% set count = 0 %}
{% for i in range(3) %}
{% set count = count + 1 %}
{% endfor %}
{{ count }}
0
{# This works correctly with namespace #}
{% set ns = namespace(count=0) %}
{% for i in range(3) %}
{% set ns.count = ns.count + 1 %}
{% endfor %}
{{ ns.count }}
3
Good to know
- Without a namespace, a
{% raw %}{% set %}{% endraw %}inside a loop does not persist outside of it. This is the main reason to reach for this function. - Access attributes with dot notation (
ns.count), and update them with{% raw %}{% set ns.count = ... %}{% endraw %}.
Try it yourself
Ready to test this? Open Developer tools > Template, paste the example into the Template editor, and watch the result update on the right. Edit the values to see how the function adapts to your own entitiesAn entity represents a sensor, actor, or function in Home Assistant. Entities are used to monitor physical properties or to control other entities. An entity is usually part of a device or a service. [Learn more].
More examples
Real scenarios where this function comes up in automations and templates. Copy any example and adapt it to your setup.
Sum energy consumption across entities
Accumulate a total from multiple sensorsSensors return information about a thing, for instance the level of water in a tank. [Learn more] inside a loop.
{% set ns = namespace(total=0) %}
{% for entity in states.sensor
| selectattr("attributes.device_class", "eq", "energy")
| list %}
{% set ns.total = ns.total + entity.state | float(0) %}
{% endfor %}
{{ ns.total | round(1) }} kWh
47.3 kWh
Find the hottest room
Track the maximum temperature and which room it belongs to.
{% set ns = namespace(max_temp=-999, room="unknown") %}
{% for sensor in states.sensor
| selectattr("attributes.device_class", "eq", "temperature")
| list %}
{% if sensor.state | float(0) > ns.max_temp %}
{% set ns.max_temp = sensor.state | float(0) %}
{% set ns.room = sensor.name %}
{% endif %}
{% endfor %}
{{ ns.room }}: {{ ns.max_temp }}°C
Kitchen: 23.5°C
Build a comma-separated list of active lights
Collect names of lights that are on into a single string.
{% set ns = namespace(names=[]) %}
{% for light in states.light | selectattr("state", "eq", "on") | list %}
{% set ns.names = ns.names + [light.name] %}
{% endfor %}
{{ ns.names | join(", ") }}
Living Room, Kitchen, Hallway
Count entities matching a condition
Count how many doors are currently open using a namespace counter.
{% set ns = namespace(open=0) %}
{% for entity in states.binary_sensor
| selectattr("attributes.device_class", "eq", "door")
| selectattr("state", "eq", "on")
| list %}
{% set ns.open = ns.open + 1 %}
{% endfor %}
{{ ns.open }} door{{ "s" if ns.open != 1 }} open
2 doors open
Still stuck?
The Home Assistant community is quick to help: join Discord for real-time chat, post on the community forum with your template and expected result, or share on our subreddit /r/homeassistant.
AI assistants like ChatGPT or Claude can also explain or fix templates when you describe what you want in plain language.
Related template functions
These functions work well alongside this one:
-
Generate a number sequence: range - Generates a sequence of numbers, like Python’s range(). Commonly used for looping a specific number of times.
-
Immediate if (ternary): iif - Shorthand for basic if/else logic in a single expression.