A few months back, Carson Gross, author of the outstanding htmx library, wrote an essay entitled “Template Fragments”; if you are unfamiliar with the concept, read that first.
The goal is to allow an application to render a partial view without defining that partial view as its own template, in its own file. A common pattern in hypermedia-driven applications (and listed “con” for them) is that every little piece that may need to be rendered on its own must be broken out into its own template. This pattern eliminates the “locality of behavior” benefits; you cannot even see your entire template together in one place. Fragment rendering eliminates that requirement.
Developing with Giraffe View Engine, we can do part of this out-of-the-box, as we can control the functions we use to create the nodes that will eventually be rendered. And, while there is not a concept of a “template fragment” in Giraffe View Engine, the term “fragment” as applied to an HTML document identifies its
Giraffe.ViewEngine.Htmx, as of v1.8.4, now supports rendering these fragments based on the
id attribute. Giraffe has the
RenderView module where its rendering functions are defined; opening the
Giraffe.ViewEngine.Htmx namespace exposes the
RenderFragment module. Its functions follow the pattern of Giraffe View Engine:
AsStringfunctions return a string
AsBytesfunctions return a byte array
IntoStringBuilderfunctions render into the provided
Each of those three modules has
htmlFromNodes if the source is a node list, and
htmlFromNode if the source is a single node. (As fragment rendering has little-to-no use in the XML world, XML rendering functions are not provided.)
One final thought - while this was built with htmx applications in mind, the concept does not require htmx. If you want to render fragments with Giraffe View Engine, using this package will allow that, whether your application uses htmx (you probably should!) or not.