How should template names be set dynamically using class based views?

帅比萌擦擦* 提交于 2019-12-04 16:49:03

问题


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']]


来源:https://stackoverflow.com/questions/15448150/how-should-template-names-be-set-dynamically-using-class-based-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!