Skip to content

Use the Template Tag

Overview

Decide where the component will be displayed by using our template tag.


Embedding a component in a template

In your Django app's HTML template, you can now embed your ReactPy component using the component template tag. Within this tag, you will need to type in the dotted path to the component.

Additionally, you can pass in args and kwargs into your component function. After reading the code below, pay attention to how the function definition for hello_world (from the previous step) accepts a recipient argument.

1
2
3
4
5
6
7
{% load reactpy %}
<!DOCTYPE html>
<html>
  <body>
    {% component "example_project.my_app.components.hello_world" recipient="World" %}
  </body>
</html>
Do not use context variables for the ReactPy component name

Our preprocessor relies on the template tag containing a string.

Do not use Django template/context variables for the component path. Failure to follow this warning can result in unexpected behavior.

For example, do not do the following:

1
2
3
4
5
<!-- This is good -->
{% component "example_project.my_app.components.hello_world" recipient="World" %}

<!-- This is bad -->
{% component dont_do_this recipient="World" %}
1
2
3
4
5
6
from django.shortcuts import render


def example_view(request):
    context_vars = {"dont_do_this": "example_project.my_app.components.hello_world"}
    return render(request, "my-template.html", context_vars)
Can I use multiple components on one page?

You can add as many components to a webpage as needed by using the template tag multiple times. Retrofitting legacy sites to use ReactPy will typically involve many components on one page.

1
2
3
4
5
6
7
8
9
{% load reactpy %}
<!DOCTYPE html>
<html>
    <body>
        <h1>{% component "example_project.my_app.components.my_title" %}</h1>
        <p>{% component "example_project.my_app_2.components.goodbye_world" class="bold small-font" %}</p>
        {% component "example_project.my_app_3.components.simple_button" %}
    </body>
</html>

Please note that components separated like this will not be able to interact with each other, except through database queries.

Additionally, in scenarios where you are trying to create a Single Page Application (SPA) within Django, you will only have one component within your <body> tag.

Where is my templates folder?

If you do not have a templates folder in your Django app, you can simply create one! Keep in mind, templates within this folder will not be detected by Django unless you add the corresponding Django app to settings.py:INSTALLED_APPS.


Last update: August 26, 2023
Authors: Mark Bakhit