简体   繁体   English

Django 视图中的动态模板

[英]Dynamic Templates in Django Views

I am wondering whether it is possible to insert template names dynamically into Django views from urls.py .我想知道是否可以从urls.py将模板名称动态插入 Django 视图中。

That is, suppose I have an app whose entire purpose is to serve as a container for various static landing pages.也就是说,假设我有一个应用程序,其全部目的是充当各种 static 登录页面的容器。 The plan is to create this app and have various entries in its urls.py correspond to paths to various landing pages.计划是创建这个应用程序,并在它的urls.py中有各种条目对应到各种登录页面的路径。 Each page would have a separate .html correspond to it.每个页面都有一个单独的.html对应。

The question is whether one could get away with writing only one (class-based or other) view for all of these templates or would there need to be a view for each page?问题是是否可以为所有这些模板只编写一个(基于类或其他)视图,或者是否需要为每个页面创建一个视图?

Django version 2.1-2.2 Django 版本 2.1-2.2

PS If there is an alternative, laconic way of accomplishing something similar, I am all ears. PS如果有另一种简洁的方式来完成类似的事情,我全神贯注。

This can be achieved with a variable in the URL and a simple function based view这可以通过 URL 中的变量和基于简单 function 的视图来实现

urls.py网址.py

from django.urls import path
from .views import landing_page_view

urlpatterns = [
    path('<slug:template_name>/', landing_page_view, name='landing_page_view'), # Your urls will be <host>/template_name
]

views.py视图.py

from django.shortcuts import render

def landing_page_view(request, template_name):
    return render(request, f'{template_name}.html') # Render view with the template corresponding with the template_name in the url 

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM