Skip to content

Defining template context

To define fake context you need to create a YAML file alongside your template file. For example, for the template big_red_button.html you need to create a file called big_red_button.yaml.

Let's imagine that your big_red_button.html template looks like this:

<a href="{{ button_link }}" class="button button--red">
    <span>{{ button_text }}</span>

The big_red_button.yaml can be something like this:

    button_text: Example link

In the same way you can provide context in more complex templates. Here is an example on how you can define fake context that pretends to be a QuerySet.

Let's assume you have the following template:

{% if my_objects.exists %}
    {{ items_title }}
        {% for obj in my_objects.all %}
                <a href="{{ }}">
                    {{ obj.title }}
        {% endfor %}
{% endif %}

You might define a yaml file similar to this to provide fake data:

name: My example pattern

    items_title: Related pages
        exists: true  # simulate `QuerySet`'s `exists` method
        all:          # simulate `QuerySet`'s `all` method
            - title: Page 1
              link: /page1
            - title: Page 2
              link: /page2

You can define a list or a dict or anything that PyYAML allows you to create in yaml format without creating a custom objects.

Last update: 2020-10-29