微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

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

如何解决如何在 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

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

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。