반응형
파이썬 Django include 태그
include 태그를 사용하면 현재 템플릿 내부에 템플릿을 포함할 수 있다.
이것은 많은 페이지에서 동일한 내용 블록이 있는 경우에 유용하다.
template.html <!DOCTYPE html> <html> <body> <h1>Hello</h1> <p>This page contains a footer in a template.</p> {% include 'footer.html' %} <p>Check out the two templates to see what they look like, and views.py to see the reference to the child template.</p> </body> </html> |
views.py from django.http import HttpResponse from django.template import loader def testing(request): template = loader.get_template('template.html') return HttpResponse(template.render()) |
footer.html <p>You have reached the bottom of this page, thank you for your time.</p> |
위의 코드를 실행하면 아래 그림과 같다.
파이썬 Django include variable
with 키워드를 사용하여 변수를 템플릿으로 보낼 수 있다.
incldue 파일에서 {{variable name}} 구문을 사용하여 변수를 참조한다:
template.html <!DOCTYPE html> <html> <body> {% include "mymenu.html" with me="TOBIAS" sponsor="W3SCHOOLS" %} <h1>Welcome</h1> <p>This is my web site.</p> <p>Check out mymenu.html to see the HTML content of the include.</p> </body> </html> |
views.py from django.http import HttpResponse from django.template import loader def testing(request): template = loader.get_template('template.html') return HttpResponse(template.render()) |
mymenu.html <div>HOME | {{ me }} | ABOUT | FORUM | {{ sponsor }}</div> |
template.html 에서 incldue with에 me 변수에 'TOBIAS'와 sponser 변수에 'W3SCHOOL'을 할당하였고 mymenu.html에서 {{me}}와 {{sponsor}}에 'TOBIAS'와 'W3SCHOOL'이 화면에 출력이 된다.
위의 코드를 실행하면 아래 그림과 같다.
이번 글에서는 파이썬 Django include에 변수 활용에 대해서 살펴보았다.
include에서 변수는 with로 활용하는 곳에서는 {{ }}로 활용하여 변수를 활용하는 것을 실습하였다.
꼭 손으로 눈으로 머리로 익히며 실습하기를 바란다.
모두 화이팅입니다.!!!
출처 : 이 글의 출처는 w3schools사이트를 참고하였으며 필자가 추가하여 정리한 글입니다.
반응형
'파이썬 > 파이썬기본문법' 카테고리의 다른 글
파이썬 Django QuerySet : Get Data (0) | 2024.03.11 |
---|---|
파이썬 Django QuerySet (0) | 2024.03.10 |
파이썬 Django 주석(Comments) (0) | 2024.03.08 |
파이썬 Django for loop variables (0) | 2024.03.07 |
파이썬 Django for loop (0) | 2024.03.06 |
댓글