[Django]-MUI with django framework

2👍

There’s an official CDN version of MUI which will help you build HTML web components using Server-Side Rendering.

You can benefit from this by adding the CSS & JS "CDN versions" into a regular HTML template, for example the below "home.html" and then render it using Django views; You can for sure pass context variables, and all what Django can offer while rendering the template.

Example home.html:

!-- Required styles for Material Web -->
<link rel="stylesheet" href="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.css">
<h1>Hello {{ dummy_context }}</h1> <!-- Render Django Context -->
<!-- Render textfield component -->
<label class="mdc-text-field mdc-text-field--filled">
  <span class="mdc-text-field__ripple"></span>
  <span class="mdc-floating-label" id="my-label">Label</span>
  <input type="text" class="mdc-text-field__input" aria-labelledby="my-label">
  <span class="mdc-line-ripple"></span>
</label>

<!-- Required Material Web JavaScript library -->
<script src="https://unpkg.com/material-components-web@latest/dist/material-components-web.min.js"></script>
<!-- Instantiate single textfield component rendered in the document -->
<script>
  mdc.textField.MDCTextField.attachTo(document.querySelector('.mdc-text-field'));
</script>

views.py:

from django.views.generic.base import TemplateView

class HomePageView(TemplateView):

    template_name = "home.html"

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['dummy_context'] = "This is a dummy context"
        return context

urls.py:

from django.urls import path

from myapp.views import HomePageView

urlpatterns = [
    path('', HomePageView.as_view(), name='home'),
]

There’s a complete list of the available MUI packages/components in the Github repo.

👤misraX

Leave a comment