When someone made a request to a website:
And that was it! Rendering the content on the server is called "server side rendering". But holy boy times have changed and things got a whole lot more bizarre.
And now, before any scripts ran on the page, your browser gets something like this:
So rendering Elm in HTML looks something like this:
h2take in a list of attributes followed by a list of children.
textjust take a String and render it to the DOM.
If we wanted to write Elm code that rendered on the server, we'd need a way to render the HTML data structure as a string on the backend. The
elm/html package wasn't designed for folks to do things like this, so we'll need to roll our own shady garbage.
For this experiment, we can create our own custom type to capture the types of HTML elements we want to render!
Here we say Html is one of two things:
In a file at
src/Ssr/Html.elm let's build an API on top of that data structure:
We'll also need to define
src/Ssr/Attributes.elm to support adding attributes and events:
With this API, we're able to write HTML that looks just like
elm/html, the only difference is we need to update our import statement to use the new module:
Ssr.Attributes are working great for building up data structures, but we can't do anything with them! We need to actually render Html:
For that reason,
Ssr.Attributes need to expose two new functions:
Now we can have two entrpoints to our app,
src/Main/Client.elm that reuse that same
Ssr.Html markup for different outputs:
When it comes time to call
src/Main/Ssr.elm is used by NodeJS to generate static HTML files, while
That results in something like this:
You can check out the source code on GitHub: https://github.com/ryannhg/rhg-dev
Thanks for reading!
February 10th, 2020