Search⌘ K
AI Features

Enhancing API with HTML Attribute Support

Explore how to enhance an HTML domain-specific language in Elixir by supporting tag attributes like class and id. Learn to update macros using unquote_splicing for flexible argument injection and practice testing new attribute features to build concise, maintainable HTML templates.

Supporting more tag attributes

To make the HTML library truly useful to the world, let’s add support for tag attributes such as class and id. Let’s extend the DSL to support an optional keyword list that gets translated into tag attributes for each macro.

For example, our goal is to support the following API:

C++
div id: "main" do
h1 class: "title", do: text("Welcome!")
div class: "row" do
div class: "column" do
p "Hello!"
end
end
button onclick: "javascript: history.go(-1);" do
text "Back"
end
end

Replacing the tag macro

Let’s revisit our Html module from the last lesson and add support for tag attributes. Now, replace the tag/2 macro on line 4, as given in the project in the previous lesson: ...