How to change the title of a page in Gleam
So, yeah. I'm posting front-end stuff as well now.
The Problem
So we have a framework called Lustre in Gleam that allows you to have multiple forms of client-side and server-side front-ends. And it is great. But it only manages a single part of the DOM with your specified id.
So if you have this index.html
:
<!doctype html>
<html lang="en">
<head>
<title>🚧 Some weird website</title>
</head>
<body>
<div id="app"></div>
<!-- here is the interesting part-->
</body>
</html>
And if you start your application in you main function like this:
let assert Ok(_) = lustre.start(app, "#app", Nil)
It will only change the <div>
with the id="app"
.
So, how would you change the title of the page?
If you move the id from the div to the <html>
tag, you would not be able to return a list of elements, as far as I understand 1.
The solution
Create a file at src/set_window_title.js
with this content:
export function set_windowTitle(title) {
document.title = title;
}
And add these to one of your Gleam files:
pub fn set_window_title(title: String) -> effect.Effect(msg) {
use _ <- effect.from
do_set_window_title(title)
}
@external(javascript, "./set_window_title.js", "set_windowTitle")
pub fn do_set_window_title(title: String) -> Nil
Now if you call the set_window_title
function as an effect, and pass it a string, it will change the title of the page, like a charm.
Thanks to Hayleigh Thompson, for the solution!
-
I am probably wrong on that. But I could not find any way to do so. ↩