장고의 템플릿 태그는 3개가 주로 쓰인다.
분기:{% if question_list %}, 반복:{% for question in question_list %}, 객체 출력:{{ question }}, {{ question.subject }}
분기문은 파이썬의 if문과 다를바 없다.
{% if 조건문1 %}
<p>조건문1에 해당되는 경우</p>
{% elif 조건문2 %}
<p>조건문2에 해당되는 경우</p>
{% else %}
<p>조건문1, 2에 모두 해당되지 않는 경우</p>
{% endif %}
중요! 반드시 {% endif %}로 분기문을 닫아주어야 한다.
역시 파이썬의 for문과 다를바 없다.
{% for item in list %}
<p>순서: {{ forloop.counter }} </p>
<p>{{ item }}</p>
{% endfor %}
중요! 반드시 {% endfor %}로 반복문을 닫아주어야 한다.
템플릿 for문 안에서는 다음과 같은 forloop 객체를 사용할 수 있다.
forloop속성
forloop.counter -> 루프내의 순서로 1부터 표시
forloop.counter0 -> 루프내의 순서로 0부터 표시
forloop.first -> 루프의 첫번째 순서인 경우 Ture
forloop.last -> 루프의 마지막 순서인 경우 Ture
객체를 출력하기 위한 태그이다.
{{ 객체 }}
그 객체에 속성이 있는 경우
{{ 객체.속성 }}
도트( . ) 으로 파이썬처럼 출력 가능
app_name = 'project_a_main'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('/estimate/write', views.estimate_write, name='estimate_write'),
]
위 path 문에서 name='' 인자에 들어있는 이름이 별칭으로 template에서 태그를 이용하여 하드코딩을 벗어날 수 있다.
<a href="{% url 'project_a_main:estimate_write' %}" class = "btn_estimate_write">견적서 작성</a>
위 코드처럼 url입력란에 태그로 별칭을 활용하면 후에 urls.py의 코드가 바뀌어도 유지보수하기 좋아진다.
{% url 'estimate_write' question.id %}
위처럼 전달할 피라미터가 있다면 공백( )후 작성하여 보낼 수 있다.
보낼 피라미터가 2개 이상일 경우
{% url 'detail' question.id pages=2 %}
다음과 같이 공백 문자 이후 덧 붙여주면 된다.
{% url 'project_a_main:estimate_write' %}에서 "project_a_main:" 은 네임스페이스로 urls.py에서 추가 할 수 있다.
urls.py
app_name = 'project_a_main'
urlpatterns = [
path('', views.IndexView.as_view(), name='index'),
path('<int:pk>/', views.DetailView.as_view(), name='detail'),
path('<int:pk>/results/', views.ResultsView.as_view(), name='results'),
path('<int:question_id>/vote/', views.vote, name='vote'),
path('/estimate/write', views.estimate_write, name='estimate_write'),
]
위 코드에서 "app_name = 'project_a_main'" 이 네임스페이스다.