Django Templates & Static files

Django templates are the presentation layer of 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 templates is a mix of static html markups and dynamic python context dictionary. Sereval template tags and filters are available to render the context dictionary.

Template Tags

  • {% extends 'base.html' %}: It extends the code of 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.
  • {% load static %}: It load the static resources under static directory.
  • {% for loop %}: It impliments a simple python for loop.
  • {% if condition %}: It impliments a simple python if condition.
  • {# comment #}: It is used for comments other than HTML comments.
  • {{ variable }}: It print the value of the given variable. A newline is not automatically included unlike Python print statement. Although html br tag can serve the same purpose.

Template Filters

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

    {{ value|filter }}
                                

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 is 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' %}"