FAM*_*ice 4 django django-templates django-static
I am doing the django tutorial on realpython https://realpython.com/get-started-with-django-1/
In one of the templates they add {% load static %} to load the static files for an app. In the same template they also load an image like this <img class="card-img-top" src="{% static project.image %}">. The static keyword here tells django to look for the filename defined in project.image in the static folder. When i remove {% load static %} the image is still displayed. So why would i need this part if the image can be perfectly rendered without it? Heres the code:
{% extends "base.html" %}
<!--{% load static %}-->
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read more</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
You are using HTML comment which is not processed by Django rather it ignores that and executes the template tag. Try using template comment {# you long comment #}.
So the code changes to
{% extends "base.html" %}
{# {% load static %} #}
{% block page_content %}
<h1>Projects</h1>
<div class="row">
{% for project in projects %}
<div class="col-md-4">
<div class="card mb-2">
<img class="card-img-top" src="{% static project.image %}">
<div class="card-body">
<h5 class="card-title">{{ project.title }}</h5>
<p class="card-text">{{ project.description }}</p>
<a href="{% url 'project_detail' project.pk %}" class="btn btn-primary">Read more</a>
</div>
</div>
</div>
{% endfor %}
</div>
{% endblock %}
Run Code Online (Sandbox Code Playgroud)
{% load static %} actually loads the tag static. This tag allows you to embed links for static files https://docs.djangoproject.com/en/3.0/howto/static-files/#configuring-static-files.
You can also create your custom tag read https://docs.djangoproject.com/en/3.0/howto/custom-template-tags/
| 归档时间: |
|
| 查看次数: |
5476 次 |
| 最近记录: |