Builtins

These variables and functions are globally available in your components.

1. Python builtins

range and pow are available by default. You can also use them as defaults for a component argument:

{# def max_value: int = pow(9) #}

Numbers: {{ range(6) | join(", ") }}
Result: {{ pow(4) }}

2. Builtin globals

2.1 app

The instance of your application.

2.2 current

The current object. Use it to access things like the logged user (current.user) or the detected locale (current.locale) or timezone (current.timezone)


3. Helpers

3.1 dom_id

Generate a stable id for a collection of objects and/or strings, suitable for use in HTML element ids.

All parts will be converted to strings and joined with underscores. If a part is an object, its class name and primary key (if available) will be used to generate a string for that part. Composite primary keys are also supported.

dom_id(Post.get(45))                     # => "post_45"
dom_id(Post.get(45), "edit")             # => "post_45_edit"
dom_id(Post.get(45), "edit", "special")  # => "post_45_edit_special"

If there is no primary key, the class name is prefixed with "new_" instead.

dom_id(Post.create())  # => "new_post"

If the object has a to_key() method, it will be used to get the key instead of the primary key. This allows you to customize the key generation for privacy-sensitive or more complex models. If it returns a composite key (tuple), the parts will be joined with underscores.

However, if this method returns None, False, or an empty value, the object will be treated as if it has no primary key.

If the object is a class rather than an instance, only the class name is used:

dom_id(Post)            # => "post"
dom_id(Post, "custom")  # => "post_custom"

3.2 is_defined

Returns True if a variable is available in the component, without an error if it doesn't.

3.3 slot_filled

Asks the component whether that slot was filled.

<div class="card">
  {% if slot_filled("title") %}
    <h2 class="card-title">{% slot title %}{% endslot %}</h2>
  {% endif %}
  {{ content }}
</div>

slot_filled is true when the caller wrote a {% fill %} for that slot, even an empty one. For the implicit content slot, test the variable: {% if content %}.


4.1 url_for

Builds a URL for the route with the given name, filling in placeholders with the given kwargs or with attributes of the given object.

url_for("Page.show", object=page)
# => "/pages/123"

url_for("Page.show", page_id=123, _anchor="section1")
# => "/pages/123#section1"

# The host is determined by the route's host constraint
# or by the application's default host.
url_for("Page.show", page_id=123, _full=True)
# => "http://www.example.com/pages/123"

The URL is percent-encoded, so pass the values as they are, not encoded (an encoded "a%20b" would become a%2520b). In the path, every character is encoded except letters, digits, -._~ and /:@!$&'()*+,;=; the arguments that are not placeholders become the query string, encoded as a form (a space is +, a / is %2F). Each placeholder value must match the placeholder's format as a whole, or url_for raises BadRoutePlaceholder: "42abc" is not an <int>, a value with a / fits only a format that accepts it, such as <path>, and a value can't make a . or .. segment ("." or ".." for /files/:name), which browsers remove. The _anchor is percent-encoded as the path is (a ? stays as it is). See Values Are Checked and Percent-Encoded.

4.2 url_is

Tells if the URL for the given route name and parameters is the same as the current URL as reported by current.request.path. This is useful for things like active links in navigation bars.

Only the paths are compared, percent-decoded and without trailing slashes: the query string and the #fragment are ignored, on both sides. Query parameters given to url_is are ignored too, so url_is("Photo.index", page=2) is True on any page of /photos.

If a current URL is not given, it defaults to current.request.path. This is useful if you want to compare to a different URL than the current request's path, for example when you are building a link to a section in the same page and want to compare against that URL instead. curr_url is a URL as in a link, percent-encoded (/tags/a%20b):

url_is("Page.show", page_id=123, curr_url="/pages/123#section1")
# => True

url_is("Page.show", page_id=123, curr_url="/pages/123?tab=photos")
# => True

url_is("Page.show", page_id=123, curr_url="/pages")
# => False

4.3 url_startswith

Tells if the current URL, as reported by current.request.path, starts with the URL for the given route name and parameters, segment by segment (/photography does not start with /photo). Paths are compared as in url_is. This is useful for things like active links to sections in navigation bars.

url_startswith("Page.show", page_id=123, curr_url="/pages/123#section1")
# => True

url_startswith("Page.show", page_id=123, curr_url="/pages/123/edit")
# => True

url_startswith("Page.show", page_id=123, curr_url="/pages/")
# => False

Every path starts with the URL of a route at /, so for a "Home" link use url_is.


5. Assets

5.1 assets.render_css

Uses the assets.collect_css() list to generate an HTML fragment with <link rel="stylesheet" href="{url}"> tags.

5.2 assets.render_js

Uses the assets.collect_js() list to generate an HTML fragment with <script type="module" src="{url}"></script> tags.

5.3 assets.render

Calls assets.render_css() and assets.render_js() to generate an HTML fragment with <link rel="stylesheet" href="{url}"> and <script type="module" src="{url}"></script> tags.

5.4 assets.collect_css

Returns a list of CSS files for the component and its children.

5.5 assets.collect_js

Returns a list of JS files for the component and its children.

5.6 render_importmap

Render a script tag containing the import map for the app's assets.

An import map is a JSON object that maps module specifiers to URLs, allowing you to use bare module specifiers in your JavaScript code. For example, with the following import map:

<script type="importmap">
{
    "imports": {
        "my-lib": "/static/my-lib.js"
    }
}
</script>

You can import my-lib in your JavaScript code like this:

import { something } from "my-lib";

The render_importmap function generates a script tag with the import map based on the app's configuration. It looks for an IMPORT_MAP configuration variable, which should be a dictionary mapping module specifiers to asset paths or URLs.

With a Content-Security-Policy, this inline script is allowed with app.importmap_csp_hash. See Content Security Policy in the Security guide.

5.7 csp_nonce

The nonce of this visitor, for the nonce attribute of an inline <script> or <style> that a Content-Security-Policy must allow:

<script nonce="{{ csp_nonce() }}">
  console.log("This one runs");
</script>

The policy must have the same value, as 'nonce-...': in a controller or a concern it is self.response.csp_nonce. The nonce is kept in the session, so asking for it gives the visitor a session cookie. See Content Security Policy in the Security guide.

5.8 csp_meta_tag

Writes a <meta name="csp-nonce"> tag with the nonce of this visitor. Turbo reads it, and gives the nonce to the style of its progress bar and to the scripts of the pages it loads. Put it in the <head> of your layout, before the scripts:

{{ csp_meta_tag() }}
{{ render_importmap() }}

6. Turbo

6.1 frame / turbo_frame

Render a <turbo-frame>, the unit Turbo navigates and replaces on its own.

ids are passed to dom_id to generate the frame's id.

Use it two ways from a template. As an expression for an empty or lazily loaded frame:

{{ frame(post, src=url_for("Posts.show", post=post), loading="lazy") }}

or as the frame tag to wrap content, with the same arguments:

{% frame post %}
  {{ post.title }}
{% endframe %}

src loads the frame's content from a URL, loading="lazy" defers that load until the frame scrolls into view, and target sends the frame's own navigations to another frame. Any extra keyword becomes an attribute, with underscores turned into dashes (data_turbo="false" -> data-turbo="false").

6.2 stream / turbo_stream

Build <turbo-stream> fragments, the unit of a Turbo Stream update.

Call an action method with a target and either a Jx component (rendered through the catalog with its props) or ready-made html:

turbo_stream.append("messages", "Message.jx", message=msg)
turbo_stream.replace(post, component="posts/Post.jx", post=post)
turbo_stream.remove("message_1")

replace and update take method="morph" to morph the target instead of swapping it.

target is an element id, or a model instance (its dom_id is used). Pass targets with a CSS selector instead to act on every matching element.

In a template, the stream tag takes the action and the same arguments, and its body is the content:

{% stream "append", "messages" %}
    <li>{{ message.body }}</li>
{% endstream %}

Broadcast the result over a stream for a live update, or return it from a controller as a text/vnd.turbo-stream.html response - the same fragment serves both. Concatenate several to send more than one operation at once.

The instance is also callable - turbo_stream("append", target, ...) - which is equivalent to the matching action method.