Routing | Django LiveView

If you want to move from one page to another, you can use the page controller and the changePage action.

For example, you can create a link to the about me page.

<a
    data-action="click->page#changePage"
    data-page="about_me"
    href="{% url "about me" %}" <!-- Optional -->
    role="button" <!-- Optional -->
   >Go to about me page</a>
  • data-action: Indicates that the element is an action. click to capture the click event. page#changePage to call the changePage function of the page controller.

  • data-page: Indicates the name of the page to which you want to move. The name is the same as the name of the action file. For example, actions/about_me.py.

  • href: Optional. It is recommended to use the href attribute to improve SEO or if JavaScript is disabled.

  • role: Optional. It is recommended to use the role attribute to improve accessibility or if JavaScript is disabled.

Or use a button for it.

<button
    data-action="click->page#changePage"
    data-page="about_me"
   >Go to about me page</button>

Send data

If you want to send data to the next page, you can use the data- attribute. All datasets will be sent.

For example, you can create a link to the blog single page with the slug of the article.

<a
    data-action="click->page#changePage"
    data-page="blog_single"
    data-slug="{{ article.slug }}"
    href="{% url "blog single" slug=article.slug %}" <!-- Optional -->
    role="button" <!-- Optional -->
   >See article</a>

To receive the data in action blog_single.py you can use the client_data parameter with the data key.

@enable_lang
@loading
async def send_page(consumer, client_data, lang=None):
    slug = client_data["data"]["slug"]
    # ...

Here you can see a typical example of a single page of a blog.

@enable_lang
@loading
async def send_page(consumer, client_data, lang=None):
    # Nav
    await update_active_nav(consumer, "blog")
    # Main
    my_context = await get_context(consumer=consumer, slug=client_data["data"]["slug"])
    html = await get_html(template, my_context)
    data = {
        "action": client_data["action"],
        "selector": "#main",
        "html": html,
    }
    data.update(my_context)
    await consumer.send_html(data)