Templates

  • Template μ–Έμ–΄λŠ” 각 framework λ§ˆλ‹€ λ‹€λ₯΄λ‹€

  • Django의 template μ–Έμ–΄λŠ” DTL !

DTL (Django Template Language)

Ground Rule

: 연산은 DTL이 μ•„λ‹Œ views.py 의 context둜 κ³„μ‚°λœ κ²°κ³Όλ₯Ό DTL은 λ‹¨μˆœνžˆ 좜λ ₯ν•˜λŠ” μ—­ν• λ§Œ ν•˜κ²Œ ν•˜κΈ°

κΈ°λ³Έ 문법

1. 좜λ ₯ {{ }}

{{ menu }}
{{ menu.0 }}

2. 문법 {% %}

{% for menu in menus %}

{% endfor %}

3. 주석 ``

{# This is comment #}

λ°˜λ³΅λΆ„

Loops over each item in an array

  • {{ forloop.counter }}

  • {{ forloop.counter0 }}

  • `

    `

    : 배열이 λΉ„μ–΄μžˆμœΌλ©΄ 좜λ ₯ν•  λ‚΄μš© 써쀄 λ•Œ μ‚¬μš©

Loop over each item in a dictionary

Variable

Description

forloop.counter

The current iteration of the loop (1-indexed)

forloop.counter0

The current iteration of the loop (0-indexed)

forloop.revcounter

The number of iterations from the end of the loop (1-indexed)

forloop.revcounter0

The number of iterations from the end of the loop (0-indexed)

forloop.first

True if this is the first time through the loop

forloop.last

True if this is the last time through the loop

forloop.parentloop

For nested loops, this is the loop surrounding the current one

쑰건문

built-in tag, filter (|)

κ³΅μ‹λ¬Έμ„œ μ°Έκ³ ν•˜μž : https://docs.djangoproject.com/en/3.0/ref/templates/builtins/arrow-up-right

length

  • 길이 ν™•μΈν•˜κΈ°

truncatechars:num

  • 10자만 μ§€λΌμ„œ 보이기

dictsort

  • dictionary μžλ£Œν˜•μΌλ•Œ, λͺ…μ‹œν•œ keyλ₯Ό κΈ°μ€€μœΌλ‘œ μ •λ ¬

Template ν™•μž₯

pages/templates/base.html

posts.html

Template μ„€μ • - DIR

BASE_DIR

  • Linux, Windows λ“± OS에 상관없이 μ„€μ •ν•˜λ €κ³  os.path.dirname()으둜 함

DIRS λ¦¬μŠ€νŠΈμ— 경둜 μ •μ˜ 폴더 ꡬ쑰λ₯Ό 톡해 ν™•μΈν•˜κΈ°

Multiple Apps

<br

μ•žμœΌλ‘œλŠ” 항상 app을 μƒμ„±ν•˜λ©΄ λ‹€μŒκ³Ό 같은 폴더 ꡬ쑰λ₯Ό κ°€μ§„λ‹€.

1. url μ„€μ • 뢄리

각각의 app λ³„λ‘œ url을 κ΄€λ¦¬ν•œλ‹€.

  • ν”„λ‘œμ νŠΈ 폴더 urls.py μ •μ˜

  • 각 ν”„λ‘œμ νŠΈλ³„ urls.py μ •μ˜

2. templates 폴더 ꡬ쑰

  • template νŒŒμΌμ„ λ°˜ν™˜ν•˜κΈ° μœ„ν•΄μ„œ djangoλŠ” μ•„λž˜μ˜ 폴더듀을 νƒμƒ‰ν•œλ‹€.

    • DIRS 에 μ •μ˜λœ 경둜의 ν•˜μœ„ 디렉토리

    • NSTALLED_APPS λ””λ ‰ν† λ¦¬μ˜ templates ν΄λ”μ˜ ν•˜μœ„ 디렉토리 탐색

  • 이 κ³Όμ •μ—μ„œ μ€‘λ³΅λœ 파일이 μžˆλŠ” 경우, μ˜ˆμƒμΉ˜ λͺ»ν•œ κ²°κ³Όκ°€ λ‚˜νƒ€λ‚  수 μžˆλ‹€.

  • λ”°λΌμ„œ, μ•žμœΌλ‘œ λ‹€μŒκ³Ό 같은 ꡬ쑰λ₯Ό μœ μ§€ν•œλ‹€.

Form 을 ν†΅ν•œ Request 처리

  1. μ‚¬μš©μžλ“€λ‘œλΆ€ν„° 값을 λ°›μ•„μ„œ (boards/new/)

  2. λ‹¨μˆœ 좜λ ₯ν•˜λŠ” page ꡬ성 (boards/complete/)

1. μ‚¬μš©μžμ—κ²Œ form 양식 제곡

1-1 url μ§€μ •

1-2 view ν•¨μˆ˜ 생성

1-3 template

  • form tagμ—λŠ” action 속성을 μ •μ˜ν•œλ‹€

    • μ‚¬μš©μžλ‘œλΆ€ν„° λ‚΄μš”μ„ λ°›μ•„μ„œ μ²˜λ¦¬ν•˜λŠ” url

  • input tagμ—λŠ” name 속성을 톡해 μ‚¬μš©μžκ°€ μž…λ ₯ν•œ λ‚΄μš©μ„ 담을 λ³€μˆ˜ 이름을 μ§€μ •ν•œλ‹€

  • url μ˜ˆμ‹œ

    • /boards/complete/?title="제λͺ©μ œλͺ©"

2. μ‚¬μš©μž μš”μ²­ 처리

2-1. urls.py μ •μ˜

bords/url.py

2-2. views.py

boards/views.py

  • requestμ—λŠ” μš”μ²­κ³Ό κ΄€λ ¨λœ 정보듀이 λ‹΄κΈ΄ objectκ°€ μ €μž₯λ˜μ–΄ μžˆλ‹€

2-3. template

+

Tip) project μ‰½κ²Œ λ§Œλ“€κΈ°!

Last updated

Was this helpful?