根据登录、配置文件或切换来更改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

最新更新