본문 바로가기

Python_WEB/Try_Django

[Django]Rendering Any Kind of Template

반응형

CodingEntrepreneurs Django 강의 정리

get_template>

1. 지정된 변수에 있는 파일명으로 템플릿을 로드하고 template 개체를 반환한다.

 

2. 반환 값의 정확한 유형은 템플릿을 로드한 백엔드에 따라 달라진다.

 

3. 템플릿을 찾을 수 없으면 TemplateDoesNotExist 에러를 반환한다.

 

4. 템플릿이 발견되었지만 잘못된 구문이 포함된 경우 TemplateSyntax/Error 에러를 반환한다.

 

views>

from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import get_template

# Model View Template (MVT)
# Dont Repeat Yourself = DRY
def home_page(request):
    my_title = "Hello there ..."
    context = {"title": my_title}
    template_name = "title.txt"
    template_obj = get_template(template_name)
    rendered_string = template_obj.render(context)
    # print(rendered_string)
    # doc = "<h1>{title}</h1>".format(title=my_title)
    # django_render_doc = "<h1>{{ title }}</h1>".format(title=my_title)
    return render(request, "hello_world.html", {"title": rendered_string})


def about_page(request):
    return render(request, "about.html", {"title": "About Us"})


def contact_page(request):
    return render(request, "hello_world.html", {"title": "Contact Us"})


def example_page(request):
    context = {"title": "Example"}
    template_name = "hello_world.html"
    template_obj = get_template(template_name)
    rendered_item = template_obj.render(context)
    return HttpResponse(rendered_item)

 

hello_world.html>

<!doctype html>
<html lang="en">

<head>
    <!-- Required meta tags -->
    <meta charset="utf-8">
    <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">

    <!-- Bootstrap CSS -->
    <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
        integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk" crossorigin="anonymous">

    <title>{% block head_title %} Replace this value {% endblock %} CFE</title>
</head>

<body>
    <div class="container">
        <div class="row">
            <div class="col-6 mx-auto">
                <h1>{{ title }}</h1>
                {% block content %}
                Replace this value
                {% endblock %}
            </div>
        </div>
    </div>


    <!-- Optional JavaScript -->
    <!-- jQuery first, then Popper.js, then Bootstrap JS -->
    <script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
        integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
        crossorigin="anonymous"></script>
    <script src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
        integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
        crossorigin="anonymous"></script>
    <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
        integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
        crossorigin="anonymous"></script>
</body>

</html>

 

title.txt>

{{ title }}--other data

 

urls>

"""try_django URL Configuration

The `urlpatterns` list routes URLs to views. For more information please see:
    https://docs.djangoproject.com/en/3.0/topics/http/urls/
Examples:
Function views
    1. Add an import:  from my_app import views
    2. Add a URL to urlpatterns:  path('', views.home, name='home')
Class-based views
    1. Add an import:  from other_app.views import Home
    2. Add a URL to urlpatterns:  path('', Home.as_view(), name='home')
Including another URLconf
    1. Import the include() function: from django.urls import include, path
    2. Add a URL to urlpatterns:  path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path, re_path  # url

from .views import (
    home_page,
    about_page,
    contact_page,
    example_page,
)

urlpatterns = [
    path("", home_page),
    path("page", about_page),
    path("pages", about_page),
    re_path(r"^pages?/$", about_page),
    re_path(r"^about/$", about_page),
    path("contact/", contact_page),
    path("example/", example_page),
    path("admin/", admin.site.urls),
]

 

적용 스크린샷>

반응형

'Python_WEB > Try_Django' 카테고리의 다른 글

[Django]Built-In Template Tags  (0) 2020.06.14
[Django]Template Context Processors  (0) 2020.06.14
[Django]Stay DRY with Templates  (0) 2020.06.14
[Django]Render Context in Templates  (0) 2020.06.13
[Django]Add Bootstrap  (0) 2020.06.13