How to create reusable components for UI in Django

1.3k Views Asked by At

I am building a project in Django which has 5 different applications inside it. Some applications are falling under same pattern and some are not. Can I create a UI components using bootstrap on the top of all these applications to reuse over the entire project. Any help would be appreciated.. Thanks in advance

2

There are 2 best solutions below

0
SLDem On

Usually that is done by creating a base template and making other templates inherit from it like this:

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>

then you will make any other template and extend it with 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 %}
1
Jacco Broeren On

Paste your component in an empty html file and then use an include statement to load that file into you template html.

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

This way you can insert you components more dynamically throughout your project.