본문 바로가기
파이썬/파이썬기본문법

파이썬 django template variable

by flycoding 2024. 3. 2.
반응형

파이썬 django template variable

django 템플릿에서는 {{}}개의 괄호 안에 변수를 넣어 렌더링할 수 있다:

template.html

<!DOCTYPE html>
<html>
<body>

<h1>Hello {{ firstname }}, how are you?</h1>

<p>In views.py you can see how to create the variable.</p>
<p>In template.html you can see how to use the variable.</p>

</body>
</html>      
view.py

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'firstname': 'Linus',
  }
  return HttpResponse(template.render(context, request))     

위의 코드를 실행하면 아래 그림과 같다.

파이썬 django template variable

 

파이썬 django view에서 변수 생성

위 예제의 변수 이름은 보기를 통해 템플릿으로 전송되었다:

views.py

from django.http import HttpResponse
from django.template import loader

def testing(request):
  template = loader.get_template('template.html')
  context = {
    'firstname': 'Linus',
  }
  return HttpResponse(template.render(context, request))   

위의 보기에서 볼 수 있듯이 context라는 이름의 개체를 생성하여 데이터로 채우고 template.render() 함수에서 첫 번째 매개 변수로 보낸다.

 

파이썬 django template에서 변수 생성

{% with %} 템플릿 태그를 사용하여 템플릿에 변수를 직접 생성할 수도 있다.

변수는 다음과 같이 {% end with %} 태그가 나타날 때까지 사용할 수 있다:

templates/template.html:

<!DOCTYPE html>
<html>
<body>

{% with firstname="Tobias" %}
<h1>Hello {{ firstname }}, how are you?</h1>
{% endwith %}

</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())          

위의 코드를 실행하면 아래 그림과 같다.

파이썬 django template에서 변수 생성

 

파이썬 Django model로부터 데이터

위의 예제는 템플릿에서 변수를 생성하고 사용하는 방법에 대한 쉬운 접근 방식을 보여주었다.

일반적으로 템플릿에서 사용하려는 대부분의 외부 데이터는 모델에서 가져온 것이다.

이전 장에서는 Member(멤버)라는 모델을 만들었고, 이 모델은 이 튜토리얼의 다음 장에서 많은 예에서 사용할 것이다.

Member 모델에서 데이터를 가져오려면 views.py 파일로 가져와 보기에서 데이터를 추출해야 한다:

members/views.py:

from django.http import HttpResponse, HttpResponseRedirect
from django.template import loader
from .models import Member

def testing(request):
  mymembers = Member.objects.all().values()
  template = loader.get_template('template.html')
  context = {
    'mymembers': mymembers,
  }
  return HttpResponse(template.render(context, request))

 

이제 템플릿의 데이터를 사용할 수 있다:

templates/template.html:

<!DOCTYPE html>
<html>
<body>

<ul>
  {% for x in mymembers %}
    <li>{{ x.firstname }}</li>
  {% endfor %}
</ul>

<p>In views.py you can see how to import and fetch members from the database.</p>

</body>
</html>        

 

위의 코드를 실행하면 아래 그림과 같다.

파이썬 Django 모델 데이터 활용 예제

 

Django 템플릿 태그 {% for %}을(를) 사용하여 구성원을 루프한다.
템플릿 태그에 대해서는 다음 장에서 자세히 알아보겠다.

 

이번 글에서는 파이썬 Django Template에서 변수를 생성하고 활용하는 방법에 대해서 살펴보았다.

파이썬 Django 변수를 활용하는 방법, 특히 템플릿에서 변수를 활용하는 방법, 뷰에서 변수를 생성하는 방법 등에 관해서 실습하였다.

꼭 손으로 눈으로 머리로 익히며 실습하기를 바란다.

모두 화이팅입니다.!!!

 

출처 : 이 글의 출처는 w3schools사이트를 참고하였으며 필자가 추가하여 정리한 글입니다.

반응형

댓글