How Django Templates Work (with Examples)

Django is a powerful web framework that simplifies the process of building web applications. One of the key features of Django is its template system, which allows developers to separate the design and structure of a web page from the underlying code. In this blog post, we will explore how Django templates work and provide examples to help you understand how to use them effectively.

### Understanding Django Templates

Django templates are text files that contain a mixture of HTML, CSS, and template tags. These template tags allow you to insert dynamic content into your web pages, such as variables, loops, and conditional statements. When a user requests a page from your Django application, the template engine processes the template and renders the final HTML output.

### Example 1: Displaying Variables

Let’s start with a simple example of how to display variables in a Django template. Suppose we have a view that passes a variable called “name” to a template. We can use the double curly braces syntax to insert the value of the variable into the HTML output:

“`html



Hello, {{ name }}

Hello, {{ name }}



“`

In this example, the value of the “name” variable will be displayed in both the title and heading of the web page.

### Example 2: Using Loops

Django templates also support looping through lists or dictionaries. For example, if we have a list of names that we want to display on a web page, we can use a for loop in our template:

“`html



Names

    {% for name in names %}

  • {{ name }}
  • {% endfor %}



“`

In this example, the template will iterate through the “names” list and display each name as a list item.

### Conclusion

Django templates provide a flexible and efficient way to create dynamic web pages. By separating the design and logic of your web application, you can easily maintain and update your codebase. We hope that these examples have helped you understand how Django templates work and how you can use them in your own projects. Happy coding!