I would like to allow the user to have the ability to change the theme based on the following factors:
- Anonymous
- Check localStorage and if empty use default else use localStorage
- Authenticated
- Check localStorage and if empty use user profile setting
I have it all working except for Authenticated users, I don’t know how to check localStorage.
JavaScript
x
18
18
1
{% if user.is_authenticated %}
2
<body class="theme-{{user.profile.theme}}">
3
// How can I check localStorage.getItem('theme') and if null use {{user.profile.theme}}
4
5
{% else %}
6
<body>
7
<script>
8
var theme = localStorage.getItem('theme')
9
if(theme == 'light'){
10
document.body.classList.add("theme-light")
11
} else if (theme == 'dark'){
12
document.body.classList.add("theme-dark")
13
} else {
14
document.body.classList.add("theme-light")
15
}
16
</script>
17
{% endif %}
18
Advertisement
Answer
Here is updated code
JavaScript
1
25
25
1
<body>
2
</body>
3
<script>
4
var user_theme;
5
const body = document.body;
6
var theme = localStorage.getItem('theme')
7
8
// check if user is authenticated & it have theme
9
{% if user.is_authenticated %}
10
user_theme = "{{user.profile.theme}}";
11
{% endif %}
12
13
if(theme){
14
if(theme == 'light'){
15
body.classList.add("theme-light");
16
} else if (theme == 'dark'){
17
body.classList.add("theme-dark");
18
} else {
19
body.classList.add("theme-light");
20
}
21
}else if(user_theme){
22
body.classList.add(user_theme);
23
}
24
</script>
25
above code will add localstorage theme first if it exists else it will add authenticated user theme if user is authenticated