在 Django 模板中,include 标签用于在模板中包含其他模板的内容。这有助于将重复的代码片段封装成可复用的模块。include 标签的语法如下:
{% include "template_name.html" %}
其中,template_name.html 是要包含的模板文件的路径。
有几种不同的方法可以使用 include 标签,让我们一一介绍并结合代码说明:
首先,我们来看一个基本的 include 标签用法:
main_template.html:
<!DOCTYPE html>
<html>
<head>
<title>Main Template</title>
</head>
<body>
<h1>Main Template Content</h1>
{% include "partial_template.html" %}
</body>
</html>
partial_template.html:
<p>This is a partial template included.</p>
在上述例子中,main_template.html 包含了 partial_template.html。当渲染 main_template.html 时,partial_template.html 的内容将会被包含进来。
你还可以在 include 标签中传递上下文数据。这使得被包含的模板可以访问在调用 include 时传递的变量。
main_template.html:
<!DOCTYPE html>
<html>
<head>
<title>Main Template</title>
</head>
<body>
<h1>Main Template Content</h1>
{% include "partial_template.html" with username="John" %}
</body>
</html>
partial_template.html:
<p>Hello, {{ username }}!</p>
在这个例子中,我们传递了 username="John" 作为上下文数据给 partial_template.html,因此 partial_template.html 将显示 "Hello, John!"。
除了包含整个模板文件,你还可以使用模板块(Template Blocks)来指定要包含的部分内容。
main_template.html:
<!DOCTYPE html>
<html>
<head>
<title>Main Template</title>
</head>
<body>
<h1>Main Template Content</h1>
{% block content %}
{% endblock %}
</body>
</html>
partial_template.html:
{% block content %}
<p>This is a partial template included.</p>
{% endblock %}
在这个例子中,main_template.html 定义了一个名为 content 的模板块。partial_template.html 通过 block 标签指定了它要包含的内容。当渲染 main_template.html 时,partial_template.html 中的 content 模板块将被嵌入到 main_template.html 的 {% block content %}{% endblock %} 标签处。
最后,你还可以在 include 标签中使用变量来动态指定要包含的模板名。
main_template.html:
<!DOCTYPE html>
<html>
<head>
<title>Main Template</title>
</head>
<body>
<h1>Main Template Content</h1>
{% include template_name %}
</body>
</html>
在这个例子中,template_name 变量的值将决定要包含的模板文件。
这里给出了 include 标签的主要用法和不同方法。你可以根据项目的需要选择最适合的方法来包含和组织你的模板。