Templates

  • Template language is different for each framework

  • Django's template language is DTL!

DTL (Django Template Language)

Ground Rule

: Operations should be calculated as results in views.py's context, not in DTL. DTL should only play the role of simply outputting the results.

Basic syntax

1. Output {{ }}

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

2. Syntax {% %}

3. Comments

Loops

Loops over each item in an array

  • Used to specify content to display when array is empty

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

Conditionals

built-in tag, filter (|)

Refer to the official documentation: https://docs.djangoproject.com/en/3.0/ref/templates/builtins/

length

  • Check length

truncatechars:num

  • Show only 10 characters (truncated)

dictsort

  • For dictionary data type, sort by specified key

Template Extension

pages/templates/base.html

posts.html

Template Configuration - DIR

BASE_DIR

  • Use os.path.dirname() to configure regardless of OS like Linux, Windows

Check folder structure through path definition in DIRS list

Multiple Apps

From now on, whenever you create an app, it will have the following folder structure.

1. URL configuration separation

Manage URLs for each app separately.

  • Define project folder urls.py

  • Define urls.py for each project

2. templates folder structure

  • To return template files, django searches the following folders:

    • Subdirectories of paths defined in DIRS

    • Subdirectories of templates folder in INSTALLED_APPS directories

  • If there are duplicate files in this process, unexpected results may occur.

  • Therefore, maintain the following structure from now on:

Processing Requests through Forms

  1. Receive values from users (boards/new/)

  2. Configure page to simply display (boards/complete/)

1. Provide form to users

1-1 URL specification

1-2 Create view function

1-3 template

  • Define action attribute in form tag

    • URL to process content received from users

  • In input tag, specify variable name to hold user input through name attribute

  • URL example

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

2. Process user requests

2-1. urls.py definition

boards/urls.py

2-2. views.py

boards/views.py

  • request contains an object with information related to the request

2-3. template

+

Tip) Creating project easily!

Last updated