【问题标题】:How to create reusable components for UI in Django如何在 Django 中为 UI 创建可重用组件
【发布时间】:2021-04-20 19:50:36
【问题描述】:

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

【问题讨论】:

    标签: django bootstrap-4 frontend uicomponents


    【解决方案1】:

    通常这是通过创建一个 base 模板并让其他模板继承自它来完成的,如下所示:

    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 %}
    

    【讨论】:

      【解决方案2】:

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

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

      这样您可以在整个项目中更动态地插入组件。

      【讨论】:

      • 您也可以使用 with 关键字将参数传递给子组件,例如:{% include '../components/modal.html' with msg="success" %}
      猜你喜欢
      • 2014-08-26
      • 2018-04-03
      • 2017-12-06
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-05-17
      • 2019-07-05
      相关资源
      最近更新 更多