Using Django Framework Templates and Tips


Using Django Framework Templates and Tips

What are Django Templates?

Django Framework templates are a powerful template engine used to create dynamic HTML pages. This system enables the separation of data and interface in web projects written with Python. Thanks to Django Templates, you can flexibly display your content based on data and develop dynamic, user-oriented sites.

Basic Usage: Creating and Rendering Templates

To start using Django templates, you need to define the template directory in your project's TEMPLATES setting. Then, add your template files with the .html extension into this directory. You can see how to call the template with a view function below:

from django.shortcuts import render

def home_page(request):
    data = {"message": "Hello Django Templates!"}
    return render(request, "index.html", data)

In the example above, the index.html file is returned as the template by views.py. Displaying the variable in the template content is quite easy:

<!DOCTYPE html>
<html>
<body>
    <h2>{{ message }}</h2>
</body>
</html>

Django Template Tags and Filters

Django Framework templates allow you to insert tags with {% %} and variables with {{ }}. For example, to display a list of data:

<ul>
    {% for name in names %}
        <li>{{ name|upper }}</li>
    {% endfor %}
</ul>

Here, the names tag comes from the Python dictionary and with the upper filter, all texts are converted to uppercase. You can also use control tags like if-else:

{% if user.is_authenticated %}
    <p>Welcome, {{ user.username }}!</p>
{% else %}
    <p>Please log in.</p>
{% endif %}

Conclusion and Advanced Tips

With Django Framework templates, you can manage the appearance of your web page easily and flexibly. By using template inheritance (like base.html) and creating custom filters/tags, you can make your projects more modular and sustainable. Using semantic HTML tags and correct meta usage in templates in terms of SEO will increase your site's success in search engines. Utilizing Django's template power well will provide both speed and security in your projects.