Submit templates for repl.it/templates here.

← Back to all posts
Dark and Light Modes with Flask
h
BD103 (113)

Hello! Today I have created a simple Flask app that, using cookies, allows one to set dark and light mode. You can read the following section on the programming of it, or just skip to the repl.

How it Works

If you look at the code where it says @app.route("/set"), you can see that instead of returning a simple render_template(), we first make a response. This allows you to adjust headers and other things. For our case, adjusting cookies. We use a redirect(url_for("index")) so that once you change your theme, it sends you back to the home page. Then, with res.set_cookies(name, value) we can adjust the cookies.

Then, looking at index.html under the templates folder, you can see the following code:

<link rel="stylesheet" href="/static/main.css">
{% if request.cookies.get("theme") %}
<link rel="stylesheet" href="/static/{{ request.cookies.get("theme") }}.css">
{% else %}
<link rel="stylesheet" href="/static/light.css">
{% endif %}

This first links a base stylesheet, main.css, the checks to see if request.cookies.get("theme") exists. If it doesn't, it'll return False and pass to the else statement and give the default light theme. If it is set, then it'll give a stylesheet named after the cookie.

For the themes, I used the Material Design Standard, using this article, this article, and this article. The theme picker tool was especially handy.

Sorry about the lighter post today, I'll see ya around. :P
~BD103

Edit

You may have to open the page in a new tab, as setting cookies is blocked through viewports / whatever replit uses :D