Generate Less Code by Walking the AST

Our Html module is clear and concise, but we did have to generate well over a hundred macros to make it work. Wouldn’t it be nice to generate less code but still maintain our expressive DSL where all tags can be used as macro calls? Let’s make it happen.

You might think that maintaining our DSL without generating all HTML macros sounds impossible, but step back and remember that Elixir gives you full AST access. For example, open up an iex prompt and quote a few arbitrary HTML DSL expressions, and let’s look at the results. Do not load your Html module since we are just quoting raw expressions outside the context of our library for this example.

iex>​ ast = ​quote​ ​do​​​
...>​ div ​do​​​
...>​ h1 ​ ...

Get Metaprogramming Elixir now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.