Here's how to create an HTML template file for django.
As a model, we will use the SampleModel
described in Previous article.
In the HTML file, you can use {{variable name}}
to embed the variable passed from views.py
in the HTML file.
You can also control the display contents using a function by setting {% function name argument 1 argument 2 ...%}
.
For class-based views, the list of records to display is passed to the template as model name_list
.
Use {% for%}
to extract this record list one by one and display it.
Similarly for function-based views, it's a good idea to pass the model's record list as context
to the HTML file.
app/samplemodel_list.html
{% for sample in samplemodel_list %}
<h1>{{ sample.char_sample }}</h1>
<p>{{ sample.text_sample }}</p>
{% endfor %}
For class-based views, individual records are passed to the template as model name
.
app/samplemodel_detail.html
<h1>{{ samplemodel.char_sample }}</h1>
<p>{{ samplemodel.text_sample }}</p>
Here, I explained the basics of creating HTML templates for django. Next time, I'll cover template inheritance and custom tag creation.
Recommended Posts