Изменение темы Django на основе входа в систему, профиля или переключения

Я хотел бы позволить пользователю иметь возможность изменять тему, основываясь на следующих факторах:

  • Аноним
    • Проверьте localStorage и если пусто, используйте по умолчанию, иначе используйте localStorage
  • Аутентифицированный
    • Проверьте localStorage и если пусто, используйте настройки профиля пользователя

У меня все работает, кроме аутентифицированных пользователей, я не знаю, как проверить localStorage.

{% if user.is_authenticated %}
<body class="theme-{{user.profile.theme}}">
// How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}}

{% else %}
<body>
  <script>
    var theme = localStorage.getItem('theme')
    if(theme == 'light'){
      document.body.classList.add("theme-light")
    } else if (theme == 'dark'){
      document.body.classList.add("theme-dark")
    } else {
      document.body.classList.add("theme-light")
    }
  </script>
{% endif %}

Вот обновленный код

<body>
</body>
<script>
var user_theme;
const body = document.body;
var theme = localStorage.getItem('theme') 

// check if user is authenticated & it have theme
{% if user.is_authenticated %}
  user_theme = "{{user.profile.theme}}";
{% endif %}

if(theme){
    if(theme == 'light'){
        body.classList.add("theme-light");
    } else if (theme == 'dark'){
        body.classList.add("theme-dark");
    } else {
        body.classList.add("theme-light");
    }
}else if(user_theme){
    body.classList.add(user_theme);
}
</script>

приведенный выше код сначала добавит тему localstorage, если она существует, а затем добавит тему authenticated user, если пользователь authenticated

Вернуться на верх