Welcome back, aspiring Django developers! Today, we're diving into one of the most powerful features of Django - Template Tags. Let's get started! π―
Template tags are functions that allow you to create dynamic web pages. They help in manipulating the template context and generating custom HTML. In Django, there are two types of template tags: Built-in Template Tags and Custom Template Tags.
The if tag checks a condition and renders the content within the {% if %} and {% endif %} tags if the condition is true.
{% if user.is_authenticated %}
Welcome, {{ user.username }}!
{% else %}
Please log in.
{% endif %}The for tag loops through a list, queryset, or dictionary and generates HTML for each item.
{% for post in posts %}
<h2>{{ post.title }}</h2>
<p>{{ post.content }}</p>
{% endfor %}What does the `if` tag do in Django?
What does the `for` tag do in Django?
Let's build a simple blog app and use the if and for tags to display posts.
{% load static %}
{% block content %}
<h1>My Blog</h1>
{% if posts %}
{% for post in posts %}
<h2><a href="{% url 'post_detail' post.id %}">{{ post.title }}</a></h2>
<p>{{ post.content|safe }}</p>
{% endfor %}
{% else %}
<p>No posts found.</p>
{% endif %}
<p><a href="{% url 'post_new' %}">Write a new post</a></p>
{% endblock %}Don't forget to import and register the posts context variable in your view:
from django.shortcuts import render
from .models import Post
def blog(request):
posts = Post.objects.all()
return render(request, 'blog/blog.html', {'posts': posts})We've covered the basics of Django's built-in template tags today. In the next lesson, we'll dive into custom template tags. Stay tuned! π
Remember, practice makes perfect. Try experimenting with if and for tags in your projects and see the magic happen! π‘