Reputation: 11696
In the Django tutorial (part 3), they have the following syntax for a template:
{% if latest_poll_list %}
<ul>
{% for poll in latest_poll_list %}
<li><a href="/polls/{{ poll.id }}/">{{ poll.question }}</a></li>
{% endfor %}
</ul>
{% else %}
<p>No polls are available.</p>
{% endif %}
Can someone explain exactly hwo the {% something %} syntax is supposed to work? Thank you for your help!
Upvotes: 2
Views: 679
Reputation: 14863
They are template-tags. In the relevant part of the actual Python-code the tutorial does this:
from django.http import HttpResponse
from django.template import RequestContext, loader
from polls.models import Question
def index(request):
latest_question_list = Question.objects.order_by('-pub_date')[:5]
template = loader.get_template('polls/index.html')
context = RequestContext(request, {
'latest_question_list': latest_question_list,
})
return HttpResponse(template.render(context))
This is the view. In this view they populate latest_question_list
with the five newest questions from the database. Then the view is told to render the output with these values.
The view then loads the template (the code you posted) and replaces the tags/placeholders with actual data from the corresponding object.
The template-tags should be pretty self-explainable. The first line checks if there are any questions provided. If it is, loop them and {{ poll.id }}
etc will then be replaced by the actual data from the query.
This is more or less the "core" of this type of design. The idea is to separate the logic and the markup as much as possible. You should have all your code in the views and just the plain markup and template-tags in the template-files. It provides a much cleaner environment and makes it much easier to maintain.
Upvotes: 4