How should template names be set dynamically using

2020-06-08 15:32发布

问题:

I've searched through the ref and topics of the class based views Django documentation(Django 1.4) but I haven't found any mentioning of this. How do I set template names dynamically using class based views? I'm looking for the class-based equivalent of the following setup:

urls.py

from django.conf.urls.defaults import *
from mysite.views import dynamic

urlspatterns = patterns('', 
    url(r'^dynamic/(?P<template>\w+)/$', dynamic),)
)

views.py

from django.shortcuts import render_to_response

def dynamic(request, template):
    template_name = "%s.html" % template 
    return render_to_response(template_name, {})

回答1:

You need to define get_template_names that returns list of template_names.

from django.views.generic import TemplateView

class DynamicTemplateView(TemplateView):

    def get_template_names(self):
        return ['%s.html' % self.kwargs['template']]