简体   繁体   中英

Dynamic Templates in Django Views

I am wondering whether it is possible to insert template names dynamically into Django views from urls.py .

That is, suppose I have an app whose entire purpose is to serve as a container for various static landing pages. The plan is to create this app and have various entries in its urls.py correspond to paths to various landing pages. Each page would have a separate .html correspond to it.

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

PS If there is an alternative, laconic way of accomplishing something similar, I am all ears.

This can be achieved with a variable in the URL and a simple function based view

urls.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

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 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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