Builtin Globals
dom_id
dom_id(*parts, random=False)
Makes the id of an HTML element from texts and objects, joined with underscores:
{#def post #}
<article id="{{ dom_id(post) }}">
<h2>{{ post.title }}</h2>
<a href="#{{ dom_id(post, 'comments') }}">Comments</a>
</article>
renders to
<article id="post_45">
<h2>Hello</h2>
<a href="#post_45_comments">Comments</a>
</article>
Each part of the id depends on what you give it:
| Part | Result |
|---|---|
| A text or a whole number | The same value: dom_id("row", 3) is row_3 |
| An object | The name of its class and its key: post_45 |
| An object without a key | new_ and the name of its class: new_post |
| A class | Its name: dom_id(Post) is post |
The key of an object is its pk or its id. To use another value, give your class a to_key() method that returns it.
The same arguments always give the same id, so other code can find the element: a <label>, a script, or a test.
With random=True, the id ends with a random text, different each time. Use it when an element needs an id but nobody else has to know it:
{#def name, label="", id="" #}
{% set input_id = id or dom_id("input", name, random=True) %}
{% if label %}
<label for="{{ input_id }}">{{ label }}</label>
{% endif %}
<input id="{{ input_id }}" name="{{ name }}" {{ attrs.render() }} />
renders to something like
<label for="input_email_3f2a9c1b04d7">Email</label>
<input id="input_email_3f2a9c1b04d7" name="email" />
Note
A random id changes every time the component is rendered. Don't use it for an element that other code has to find later.
You can also use it in Python: from jx import dom_id.