# 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.

```interlace-demo
KeyDemo
```

## Syntax

```django
<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

```django
{% for item in items %}
    <div lace:key="item-{{ item.id }}">
        {{ item.name }}
    </div>
{% endfor %}
```

Conditional Rendering

```django
{% 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

```django
<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>
```
