如何在 Django 中为 UI 创建可重用的组件

问题描述

我正在 Django 中构建一个项目,其中包含 5 个不同的应用程序。有些应用程序属于相同的模式,有些则不是。我可以在所有这些应用程序的顶部使用引导程序创建一个 UI 组件,以便在整个项目中重用。任何帮助将不胜感激.. 提前致谢

解决方法

通常是通过创建一个基础模板并让其他模板继承它来完成的:

base.html

<html>
<head>
    <title>Title</title>
</head>
<body>
    <navbar> # example navbar that will be visible in each template that will extend this one
       <ul>
           <a href="#">Home</a>
           <a href="#">Contact</a>
           <a href="#">Something else</a>
       </ul>
    </navbar>
    {% block content %} # here is where the content of child templates will be seated
    {% endblock %}
</body>
</html>

然后您将制作任何其他模板并使用base.html

扩展

your_other_template.html

{% extends 'base.html' %} # this line makes sure your child templates inherit the html of your main template
{% block content %} # here is where you will place the content of your other templates
    <h1> This is the content of a child template </h1>
{% endblock %}
,

将您的组件粘贴到一个空的 html 文件中,然后使用 include 语句将该文件加载到您的模板 html 中。

https://docs.djangoproject.com/en/3.1/ref/templates/builtins/#include

通过这种方式,您可以在整个项目中更动态地插入组件。