UNC BACS 350

Web Apps with Python/Django

Logo

View Inheritance Design Pattern

Overview

Goals

Build a common theme that is used on all pages on a website.

Provide one place for each feature.

Encapsulate all common logic for reuse.

Build views without thinking.

Use Bootstrap to create high visual impact.

Use Partial Templates to organize your code logic.

Use Template Blocks to override default behavior.

Provide useful default behavior.

Steps

Create a series of templates

theme.html
_header.html
_footer.html
_navbar.html
_user.html

Define blocks for page composition

title
navbar
user
header
content
footer

Template

Theme

theme.html

```html

<title>{% block title %}NO TITLE{% endblock title %}</title>

<link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/css/bootstrap.min.css" rel="stylesheet">
<script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.1/dist/js/bootstrap.bundle.min.js"></script>
<link href="/static/style.css" rel="stylesheet">

{% block navbar %}
{% include '_navbar.html' %}
{% endblock navbar %}


{% block header %}
{% include '_header.html' %}
{% endblock header %}


{% block content %}
<div class="bg-danger text-light text-center">
    <h1>Workshop Theme Page</h1>
    <p>This is a demo of a base theme page with no content or inheritance.</p>
</div>
{% endblock content %}


{% block footer %}
{% include '_footer.html' %}
{% endblock footer %}

```

Header

header.html

```html

View Workshop

```

Footer

footer.html

```html

```

Navbar

navbar.html

```html

```

User Info

user.html

```html {% if user.is_authenticated %}

{% else %}

<li class="nav-item active">
    <a href="{% url 'login' %}" class="nav-link p-2 m-2">
        <i class="fas fa-sign-in-alt"></i> Log In
    </a>
</li>

{% endif %} ```

Views

views.py

python class HtmlView(TemplateView): template_name = 'home.html'

URL Routes

urls.py

```python urlpatterns = [ path('', HtmlView.as_view(), name='home'), path('theme.html', HtmlView.as_view(template_name='theme.html'), name='theme'), ]

```