Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django Template: Make sections of template reorderable?

How can I programmatically change sections of a Django template on the fly?

Given this template:

{% for it in itemlist_1 %}
{{it.unique_display_function_1}}
{%endfor%}

{% for it in itemlist_2 %}
{{it.unique_display_function_2}}
{{it.unique_display_function_2a}}
{{it.unique_display_function_2b}}
{%endfor%}

...

{% for it in itemlist_n %}
{{it.unique_display_function_n}}
{{it.unique_display_function_n_sub_x}}
{{it.unique_display_function_n_sub_xyz}}
{%endfor%}


How could I build a generic Django template so that every time this template is rendered external settings determine what order the itemlists are rendered in the template?

So the list of n sections can appear in any order according to some external settings.

NOTE: Updated to show that each section of the template has a lot of sub-parts and is actually quite long.

like image 500
MikeN Avatar asked Dec 08 '25 03:12

MikeN


1 Answers

I'd suggest creating a list of the section names in the view corresponding to the order that the user specifies.

def view(request):
    # this list can also be built dynamically based on user preferences
    item_list = ["section_one.html", "section_two.html", "section_three.html"]
    return render_to_response('main_template.html', RequestContext(request, locals()))

Then in the template you can render each section as a sub-template like below, where the sub-templates are named a "NAME.html" format:

{%for item in item_list%}
    {% include item %}

Here's a reference for the include tag: https://docs.djangoproject.com/en/dev/ref/templates/builtins/#include

like image 155
Eron Villarreal Avatar answered Dec 10 '25 20:12

Eron Villarreal