djangomaterial-uiserver-side

MUI with django framework


Is it possible to use mui with a django framework? I would like to keep it server-side using django. I know typically mui is built with client side rendering by using a react library. I did find a cdn library in muicss.com but i'm afraid this library is outdated. I would like to use the current version 5.0 and all of it's classes/components. Any ideas?


Solution

  • 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">
    <!-- Render Django Context -->
    <h1>Hello {{ dummy_context }}</h1> 
    <!-- 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.