How to write a single view function to render multiple html from diferent urls path?

前端 未结 3 569
生来不讨喜
生来不讨喜 2021-01-24 13:24

I am trying to avoid self coping of views functions but have no idea ho to do it. My views have a minor differences and there is definitely a way to render html pages with a si

相关标签:
3条回答
  • 2021-01-24 13:47

    If your site is completely static, you may consider using a static framework, like Jekyll.

    This way you don't have to depend on the host server's features, and avoid issues that may arise when you use a complex framework like django.

    0 讨论(0)
  • 2021-01-24 13:47

    I would like to thank all people who tried to help me. Your advises inspired me for a solution. I used a code below and it works good. It appears that there is no need to create a separate view and you may use TemplateView for static html file rendering. That's exactly what I was looking for.

    from django.contrib import admin
    from django.urls import path
    from django.views.generic import TemplateView
    
    urlpatterns = [
        path('admin/', admin.site.urls),
        path('', TemplateView.as_view(template_name='index.html'), name="index"),
        path('about/', TemplateView.as_view(template_name='about.html'), name="about"),
        path('team/', TemplateView.as_view(template_name='team.html'), name="team"),
        path('contacts/', TemplateView.as_view(template_name='contacts.html'), name="contacts"),
        path('researches/', TemplateView.as_view(template_name='researches.html'), name="researches"),
        path('publications/', TemplateView.as_view(template_name='publications.html'), name="publications"),
    ]
    
    0 讨论(0)
  • 2021-01-24 13:48

    You can capture a slug in the URL and use it to determine which template to render.

    path('<slug:slug>', views.general_page, ...)
    

    ...

    def general_page(request, slug):
        return render(request, 'website/{}.html'.format(slug))
    
    0 讨论(0)
提交回复
热议问题