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.
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
It'd be easier to reorder the sections in the view:
The view:
def view(request):
context = {}
context['items'] = []
#decide the order and put the items into the context
return render_to_response('template.html',context,context_instance=RequestContext(request))
The template:
{%for itemlist in items%}
{%for item in itemlist%}
{{item.display_function}}
{%endfor%}
{%endfor%}
精彩评论