Rendering HTML with functions or a DSL instead of templates

I’ve noticed that in other languages, there is a practice of rendering HTML with functions (as in Elm) or with a DSL (as in the case of Crystal in the Lucky framework). This approach has a number of advantages over templating:

  1. HTML is parsed far more easily because there is no parsing to do: the developer writes out the AST.
  2. HTML is written in the same syntax as all your other code
  3. It is much more easier to extend your rendering - define a new function or new macro

A major effect of No. 1 is that validation of HTML becomes a lot more easier to implement. Validation in this way would have appeared a lot sooner than it appeared with EEx in the form of HEEx (which I believe only became the norm sometime last year)

No. 2 is a big advantage for me because I don’t have to deal with verbose SGML syntax, and more significantly, I have syntax highlighting, completion etc. working out of the box when I inline templates (for liveviews for example). DSLs will help reduce to complexity of editor configurations needed to deal with inline templating.

No. 3 basically means that function component like functionality was available from the beginning. No major extra effort has to be made to provide a good syntax to call functions because you just use standard Elixir syntax. Before Heex (for me at least) trivial things were duplicated and non-trivial things had a verbose function call.

Those are the first benefits that came to mind, and there may be more. Of course, there is a disadvantage, that is you first need to learn the DSL and possibly its nuances as well before you can get productive. For some this is a problem, but for most (I think at least) it is not. This is analogous to the question of DSLs for SQL queries or not in languages where ORMs are not required or aren’t the norm. Some use them, some don’t.

No other disadvantages come to mind, and there may be more, but overall it seems to me that DSLs are not inherently worse than templates in other way. There are nice to have benefits of using them though. Perhaps with DSL-like templating languages like haml you get the (some of at least) best (or maybe worst!) of both worlds.

Now the question I have is this: Why do we not use DSLs (or plain functions sans macros) for rendering HTML in Phoenix? Was it because that is what Rails did, and there weren’t any problems with it to need such a change? Or is there some other reason? I know for a fact that there are no technical limitations preventing such a approach. Though I haven’t read the book, I believe Chris McCord himself writes such a DSL in Metaprogramming Elixir.

1 Like

I’ve used Temple in the past and enjoyed it. I’d like to get back to it one day.

1 Like