lace:key
Provide unique keys for DOM morphing to preserve element identity. The two lists below
are identical apart from lace:key. Type something next to each label, rotate the order, and
watch the right column keep each row's text with its label, while the left column leaves it behind.
Each row's box holds a number typed in the browser. Press Rotate: with a key the number follows its label (and the row animates to its new spot); without one the DOM node stays put and the number is left behind. Edit a box to make it your own.
Without lace:key
With lace:key
class KeyDemo(Component):
rows: list = ["Alpha", "Bravo", "Charlie"]
def rotate(self):
self.rows = self.rows[1:] + self.rows[:1]
def inline_template(self):
return """
<div class="grid grid-cols-2 gap-4">
{# left column: no key #}
{% for row in rows %}
<div>
<span>{{ row }}</span>
<input x-init="$el.value = $el.value || '{{ forloop.counter }}'">
</div>
{% endfor %}
{# right column: keyed, and animated on reorder #}
{% for row in rows %}
<div lace:key="{{ row }}" lace:transition>
<span>{{ row }}</span>
<input x-init="$el.value = $el.value || '{{ forloop.counter }}'">
</div>
{% endfor %}
</div>
<button lace:click="rotate">Rotate order</button>
"""
Syntax
<div lace:key="unique-identifier"></div>
Purpose
When Interlace updates the DOM, it uses keys to match elements between old and new states. This prevents unnecessary recreation and maintains element state (focus, scroll position, animations).
When to use
- Items in loops that can be reordered
- Dynamic lists where items can be added/removed
- Elements with local state (input focus, scroll position)
- Sortable lists (required with lace:sort)
Examples
List Items
{% for item in items %}
<div lace:key="item-{{ item.id }}">
{{ item.name }}
</div>
{% endfor %}
Conditional Rendering
{% if show_form %}
<form lace:key="edit-form">
<input type="text" name="title" />
</form>
{% else %}
<div lace:key="display-mode">
{{ title }}
</div>
{% endif %}
Sortable List
<ul lace:sort="reorder($item, $position)">
{% for task in tasks %}
<li lace:sort:item="{{ task.id }}" lace:key="task-{{ task.id }}">
{{ task.title }}
</li>
{% endfor %}
</ul>