Skip to content

Instantly share code, notes, and snippets.

@rochacbruno
Created February 21, 2014 00:40
Show Gist options
  • Select an option

  • Save rochacbruno/9126605 to your computer and use it in GitHub Desktop.

Select an option

Save rochacbruno/9126605 to your computer and use it in GitHub Desktop.

Pre load boxes for performance and avoid content duplication.

Recommended to use OPPS_MULTISITE_FALLBACK = True and have in mind that boxes will return a list of ContainerBoxContainers instead of a list of Containers.

To preload all the container boxes of a given page and avoid duplication of content the load_boxes tag should be used, this tag will take a list of slugs and the order of slugs in that list will be the precedence to avoid repetitions.

In the base template the following block should be defined.

# templates/base.html

{% block box_loader %} {% endblock %}

<html>
...
...
</html>

It is important to define that empty block in the base template, bacause Django will render templates in that order.

Now in your extended template (the one where you are going to load the boxes):

# templates/another_template.html
{% load container_tags %}
{% block box_loader %}

   {% load_boxes 'slug1,slug2,slug3,slug4,...' as container_boxes %}

{% endblock %}

do not use spaces between slugs BAD: 'slug1, slug2, ...', GOOD: 'slug1,slug2,...'

The load_boxes will preload all the boxes in the given order with its contents and will execute a pipeline passing repeated ids to the subsequent in order to avoid repetitions between boxes on the same list.

If you want to check which boxes has been preloaded you can add a console.log to debug:

# templates/another_template.html
{% load container_tags %}
{% block box_loader %}

   {% load_boxes 'slug1,slug2,slug3,slug4,...' as container_boxes %}

    <script>
    console.log("############ Preloaded boxes ###############");
    console.log("{{container_boxes.keys|safe}}");
    console.log("############ Preloaded boxes ###############");
    </script> 

{% endblock %}

This will print in to your browser's console a list of preloaded boxes.

Now you can load boxes in the usual way, no changes needed. If the box is preloaded it will be taken from the global_request object and no database operations will be done to get the box (only its contents), also it will avoid duplications.

# load in the usual way
{% get_containerbox 'slug1' template_name='templates/slug1.html' %}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment