Django Templates 是 Django 框架中的一个重要组成部分,它允许你以非编程的方式创建复杂的 HTML 页面。以下是一些关于 Django Templates 的基础知识和使用方法。
基本结构
一个 Django Template 通常由 HTML 标签和特殊的 Django 模板标签组成。以下是一个简单的 Django Template 示例:
<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ page_header }}</h1>
<p>{{ page_content }}</p>
</body>
</html>
在上面的例子中,{{ page_title }}
、{{ page_header }}
和 {{ page_content }}
是 Django 模板变量。
变量
变量允许你在模板中插入动态内容。你可以在视图函数中定义变量,并将它们传递给模板。
from django.shortcuts import render
def home(request):
page_title = "欢迎来到我的网站"
page_header = "首页"
page_content = "这里是首页的内容。"
return render(request, 'home.html', {'page_title': page_title, 'page_header': page_header, 'page_content': page_content})
模板标签
Django 提供了许多模板标签,可以帮助你实现更复杂的功能。
{% if ... %}
标签
用于条件判断。
{% if page_title %}
<h1>{{ page_title }}</h1>
{% endif %}
{% for ... in ... %}
标签
用于循环遍历。
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
图片插入
以下是如何在模板中插入图片的示例。
<center><img src="https://cloud-image.ullrai.com/q/Golden_Retriever/" alt="Golden Retriever"/></center>
更多关于 Django Templates 的信息,请参阅本站的 Django Templates 官方文档。
# Django Templates Tutorial
Django Templates is an essential part of the Django framework that allows you to create complex HTML pages in a non-programming way. Below is some basic knowledge and usage of Django Templates.
## Basic Structure
A Django Template usually consists of HTML tags and special Django template tags. Here is a simple example of a Django Template:
```html
<html>
<head>
<title>{{ page_title }}</title>
</head>
<body>
<h1>{{ page_header }}</h1>
<p>{{ page_content }}</p>
</body>
</html>
In the above example, {{ page_title }}
, {{ page_header }}
, and {{ page_content }}
are Django template variables.
Variables
Variables allow you to insert dynamic content into your templates. You can define variables in a view function and pass them to the template.
from django.shortcuts import render
def home(request):
page_title = "Welcome to My Website"
page_header = "Home"
page_content = "This is the content of the home page."
return render(request, 'home.html', {'page_title': page_title, 'page_header': page_header, 'page_content': page_content})
Template Tags
Django provides many template tags that can help you achieve more complex functionalities.
{% if ... %}
Tag
Used for conditional judgments.
{% if page_title %}
<h1>{{ page_title }}</h1>
{% endif %}
{% for ... in ... %}
Tag
Used for looping.
<ul>
{% for item in items %}
<li>{{ item }}</li>
{% endfor %}
</ul>
Image Insertion
Here is an example of how to insert images into a template.
<center><img src="https://cloud-image.ullrai.com/q/Golden_Retriever/" alt="Golden Retriever"/></center>
For more information about Django Templates, please refer to our Django Templates official documentation.