A New Paradigm Shift
MiniHtml is a B4X library to create html markup. Instead of writing html using opening and closing tags, we declare MiniHtml object and chain it's methods to generate the attributes and finally output the object as String.Advantages
- Type-safe or more structured way to build HTML compared to raw strings
- Easier to maintain and refactor web-generation code in B4X
- Integrates well with any CSS frameworks
- Integrates well with any JavaScript frameworks
- Works well with HTMX and AlpineJS to build interactive front-ends without a heavy front-end framework
- we want to stay within B4X ecosystem
- building server-side web apps using B4J
- generating email HTML templates
- prototyping simple web UIs via B4X code
- Use B4J as a single IDE for both backend and frontend logic
- Use B4J server as live development server
- Avoid B4J IDE auto-capitalize some keywords inside String Literals which will break JavaScripts
- Easily use B4X to temporary comment out certain part of code
- Focus on writing in B4X mindset
- Direct access and mix the tag objects with B4X code
- Add this sub to our project.
B4X:Sub CreateTag (Name As String) As MiniHtml Dim tag1 As MiniHtml tag1.Initialize(Name) Return tag1 End Sub - Now we can use it to create new tags.
- To create a div tag, create a new sub as follow:
B4X:Sub Div As MiniHtml Return CreateTag("div") End Sub - Now we can create a div tag using Div sub.
B4X:Dim div1 As MiniHtml = Div.up(body1) div1.cls("d-flex align-items-center") div1.sty("height: 100vh") - It is recommend to call .up() once we have created a new MiniHtml object.
- Exceptional case for not calling .up() is when we are creating a reusable sub that return the object.
- We can chain more methods but it is more cleaner to make new method calls on new line of code.
- We can call .up() method to add the current object to an existing MiniHtml object as it's child.
B4X:Dim div1 As MiniHtml = Div.up(body1) - In this code, div1 will be added to the body1 children list.
- The parent's tag will close itself.
- Calling .build will generate and return the object as HTML text.
B4X:body1.build - The output will look like this:
HTML:<body> <div class="d-flex align-items-center" style="height: 100vh"> </div> </body>
- We can also use .Write to add raw String to the object like using StringBuilder.
B4X:Private Sub ShowIndexPage Dim doc As MiniHtml doc.Initialize("") doc.Write("<!DOCTYPE html>") doc.Write(body1.build) Response.Write(doc.ToString) End Sub
Last edited: