Django Templates & Static files

Django templates are the presentation layer of the Django web application. A templates folder is typically created under the app directory and it has .html files. A static directory can also be created under the app directory to store images, CSS, and js files.

    mysite    
        └── ...    
    myapp
        └── templates
            └── index.html
        └── static
            └── img
            └── css
            └── js
                                

Django Template Tags

Django template is a mix of static HTML markups and dynamic python context dictionary. Several template tags and filters are available to render the context dictionary.

Template Tags

  • extends 'base.html': It extends the code of the base template to any template file that sub-classes it. extends tag must be the first line if used.
  • block content: It marks the dynamic section of a template which will be described in the extending template.
  • : It loads the static resources under the static directory.
  • for item in collection: It implements a simple python for a loop.
  • if condition: It implements a simple python if condition.
  • : It is used for comments other than HTML comments.
  • : It prints the value of the given variable. A newline is not automatically included, unlike the Python print statement. Although HTML <br> tag can serve the same purpose.

Template Filters

Filters can be used to enhance the value of the context key variables.

All available filters in Django templates are as follows:

  • add
  • addslashes
  • capfirst
  • center
  • cut
  • date
  • default
  • default_if_none
  • dictsort
  • dictsortreversed
  • divisibleby
  • escape
  • escapejs
  • filesizeformat
  • first
  • floatformat
  • force_escape
  • get_digit
  • iriencode
  • join
  • json_script
  • last
  • length
  • length_is
  • linebreaks
  • linebreaksbr
  • linenumbers
  • ljust
  • lower
  • make_list
  • phone2numeric
  • pluralize
  • pprint
  • random
  • rjust
  • safe
  • safeseq
  • slice
  • slugify
  • stringformat
  • striptags
  • time
  • timesince
  • timeuntil
  • title
  • truncatechars
  • truncatechars_html
  • truncatewords
  • truncatewords_html
  • unordered_list
  • upper
  • urlencode
  • urlize
  • urlizetrunc
  • wordcount
  • wordwrap
  • yesno

Static files

Django project settings.py defines a static directory that typically houses images, CSS, and javascript files. A sample code below shows how to use the static files.

load static

In img tag use:

src = "/static/img/my_image.png"                                             

For CSS files use under link tag:

href = "/static/css/my_stylesheet.css"                          

For Javascript files use under script tag:

src = "/static/js/my_script.js"