HTML Elements
Constructing HTML elements
HTMLBuilder.jl lets you construct HTML elements in idiomatic Julia. For example, after loading the package with
julia> using HTMLBuilderyou can create a p (paragraph) element by running
julia> p("Some text.")<p>Some text.</p>
You can also pass multiple arguments to an element:
julia> p("Some text. ", "Some more text.")<p>Some text. Some more text.</p>
Rendering HTML
HTML elements are handled as Julia structs. HTMLBuilder.jl only renders plain HTML by extending the Base.write method. Therefore, to get plain HTML, simply convert your element to a string:
julia> string(p("Some text."))"<p>Some text.</p>"
Nesting elements
HTML elements can be nested. For instance, you can format text using the b (bold) and i (italic) tags:
julia> p("Some text. ", b("Some bold text."))<p>Some text. <b>Some bold text.</b></p>
Automatic indentation
Some tags include custom indentation formatting:
julia> body(dv(h1("A title"), p("Some text.")))<body> <div> <h1>A title</h1> <p>Some text.</p> </div> </body>
HTML attributes
To include the HTML attributes of an element, pass a NamedTuple as the first argument with the names and values of the attributes. We can first define paths urls to the HTMLBuilder.jl logo
julia> src = "https://raw.githubusercontent.com/rafaelbailo/HTMLBuilder.jl/refs/heads/main/docs/src/assets/logo.svg";and to this documentation
julia> href = "https://rafaelbailo.github.io/HTMLBuilder.jl/";Then, an img element can be constructed as
julia> img((; src, alt = "The HTMLBuilder.jl logo", width = 500))<img src='https://raw.githubusercontent.com/rafaelbailo/HTMLBuilder.jl/refs/heads/main/docs/src/assets/logo.svg' alt='The HTMLBuilder.jl logo' width='500'>
Any additional arguments passed to the element will be treated as content. An a (hyperlink) element with text can be constructed as
julia> a((; href), "The HTMLBuilder.jl documentation")<a href='https://rafaelbailo.github.io/HTMLBuilder.jl/'>The HTMLBuilder.jl documentation</a>
Registering your own HTML elements
If you need to use an HTML element not exported by HTMLBuilder.jl, you can simply add your own with the @register macro:
julia> @register customelementHTMLElement{Val{:customelement}}
Now you can work with the new element as you would with any other:
julia> dv(customelement("Some content."), p("Some more content."))<div> <customelement>Some content.</customelement> <p>Some more content.</p> </div>