Django

Working with Template

Working with Templates in Django: Bringing Your Web Pages to Life

Templates in Django are your go-to tool for designing web pages that display dynamic content. They separate your HTML from your backend code, making your project organized and scalable.

This post will guide you through how to work effectively with Django templates.


️ What Is a Template?

A template is an HTML file with placeholders for dynamic content. When a view renders a template, Django fills in these placeholders with data and sends the resulting HTML to the user’s browser.


️ Setting Up Your Templates Folder

By default, Django looks for templates in a directory named templates. You can create this folder inside your app or project directory.

Example structure:

arduino
myproject/
myapp/
templates/
myapp/
home.html

Tip: Organize templates by app name inside the templates folder to avoid conflicts.


✨ Using Variables in Templates

Placeholders for variables are marked with double curly braces: {{ variable_name }}.

Example home.html:

html
<h1>Welcome, {{ user_name }}!</h1>

Rendering a Template from a View

In your view function, use the render() shortcut:

python
from django.shortcuts import render

def home(request):
context = {'user_name': 'Alice'}
return render(request, 'myapp/home.html', context)

context is a dictionary where keys are variable names used in the template, and values are their data.


Template Inheritance

Avoid repeating code by creating a base template with common elements like header and footer.

base.html:

html
<!DOCTYPE html>
<html>
<head>
<title>{% block title %}My Site{% endblock %}</title>
</head>
<body>
<header>My Website Header</header>

<main>
{% block content %}{% endblock %}
</main>

<footer>Footer info</footer>
</body>
</html>

home.html (extends base):

html
{% extends "myapp/base.html" %}

{% block title %}Home Page{% endblock %}

{% block content %}
<p>Welcome, {{ user_name }}!</p>
{% endblock %}


️ Control Structures in Templates

Templates support logic tags like:

  • If statements:

html
{% if user_name %}
Hello, {{ user_name }}!
{% else %}
Hello, Guest!
{% endif %}
  • For loops:

html
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>

Template Filters

Filters modify variables’ output, e.g.,

html
<p>{{ user_name|lower }}</p> <!-- outputs name in lowercase -->
<p>{{ number|floatformat:2 }}</p> <!-- formats float with 2 decimals -->

Summary

Template Feature Usage Example
Variable {{ variable }}
If Condition {% if condition %}...{% endif %}
For Loop {% for item in list %}...{% endfor %}
Template Inheritance {% extends "base.html" %}
Filters `{{ variable

Leave a Reply

Your email address will not be published. Required fields are marked *