SkillAgentSearch skills...

PageBuilder

An arduino library to create html string in the sketch for ESP8266/ESP32 WebServer.

Install / Use

/learn @Hieromon/PageBuilder

README

PageBuilder - HTML assembly aid for ESP8266/ESP32 WebServer

GitHub release Build Status arduino-library-badge PlatformIO Registry License

An arduino library to create html string in the sketch for ESP8266/ESP32 WebServer.

PageBuilder is an Arduino library class dedicated to the ESP8266WebServer or the WebServer(ESP32) for easily generating HTML pages and sending them to the client.

Features

  • Ability to completely separate HTML structure and the web page generation logic in the sketch
  • No need for inline coding of URI access handler of ESP8266WebServer class or ESP32's WebServer class
  • Fixed HTML statement parts like template can be allocated as PROGMEM
  • Its HTML source can be stored SPIFFS and obtain automatically
  • Arbitrary token can be specified inline HTML statement
  • Automatically sent to client for HTML page are generated

Ordinary sketch | Sketch by PageBuilder
----------------|----------------------
ordinary_sketch | pagebuilder_sketch

Works on

  • For ESP8266
    Generic esp8266 module and other representatives works fine. ESP8266 Arduino core 2.4.0 or higher is necessary.
  • For ESP32
    Arduino core for ESP32 supported boards works fine. ESP32 Arduino core 1.0.0 or higher is necessary.

Installation

Download this file as a zip, and extract the resulting folder into your Arduino Libraries folder. See Installing Additional Arduino Libraries.
Required Arduino IDE is current upstream at the 1.8 level or later, and also ESP8266 Arduino core or ESP32 Arduino core.

Example

  • A most simple example. - No URI handler is needed, only the URI path and html coded.
#include "PageBuilder.h"

// root page
PageElement ROOT_PAGE_ELEMENT("<a href=\"/hello\">hello</a>");
PageBuilder ROOT_PAGE("/", {ROOT_PAGE_ELEMENT});
// /hello page
PageElement HELLO_PAG_ELEMENT("Hello, world!<p><a href=\"/bye\">bye</a></p>");
PageBuilder HELLO_PAGE("/hello", {HELLO_PAG_ELEMENT});
// /bye page
PageElement BYE_PAGE_ELEMENT("Good bye!");
PageBuilder BYE_PAGE("/bye", {BYE_PAGE_ELEMENT});

ROOT_PAGE.insert(Server);     // Add root page
HELLO_PAGE.insert(Server);    // Add /hello page
BYE_PAGE.insert(Server);      // add /bye page
  • Share multiple elements on different pages.
#include "PageBuilder.h"

static const char _HEAD[] PROGMEM = "<html>" ;
static const char _BODY[] PROGMEM = "<body>This is {{PAGE}}.</body>";
static const char _FOOT[] PROGMEM = "</html>";

String setBody1(PageArgument& args) {
	return String("Page1");
}

String setBody2(PageArgument& args) {
	return String("Page2");
}

PageElement header( _HEAD );
PageElement body1( _BODY, { {"PAGE", setBody1} });
PageElement body2( _BODY, { {"PAGE", setBody2} });
PageElement footer( _FOOT );

PageBuilder Page1( "/page1", {header, body1, footer} );
PageBuilder Page2( "/page2", {header, body2, footer} );
  • HTML source stored in SPIFFS.

The following screenshot is an example PageBuilder sketch using HTML source stored in SPIFFS. It scan the nearby signal and connect the ESP8266 to the specified access point.
This case is FSPage.ino example sketch in this repository.

<kbd>Join to WiFi</kbd> <kbd>Connect to WiFi</kbd> <kbd>Welcome</kbd>

Usage

Data structure of PageBuilder

In order to successfully generate an HTML page using PageBuilder please understand the data structure of PageBuilder.
PageBuilder library consists of three objects that are related to each other as the below. PageBuilder inherits RequestHandler provided from ESP8266WebServer (in the ESP8266 arduino core) or WebServer (in the ESP32 arduino core) library and is invoked from ESP8266WebServer/WebServer in response to http requests. PageBuilder owns its URI string and multiple PageElement objects.
Source strings of HTML are owned by PageElement (mold in the figure). Its string contains an identifier called a token. The token appears as {{ }} in the middle of the source HTML string (_token in the figure). The tokens are paired with functions to replace them with actual HTML sentences. When URI access has occurred server from the client, its paired function is invoked by extension of handleClient() method then the token will replace to actual statement to complete the HTML and sends it. PageElement can have multiple tokens (i.e., it can define several tokens in one HTML source element).
default_data_structure
To properly generate a web page, you need to code its function that replaces the token with HTML, and its function must return a String.

String AsName(PageArgument& args) {      // User coded function
...    ~~~~~~
  return String("My name");
}
String AsDaytime(PageArgument& args) {   // User coded function
...    ~~~~~~~~~
  return String("afternoon");
}

// Source HTML string
const char html[] = "hello <b>{{NAME}}</b>, <br>Good {{DAYTIME}}.";
...                             ^^^^                   ^^^^^^^
...                             token                  token

PageElement header_elem("<html><body>");
PageElement footer_elem("</body></html>");
PageElement body_elem(html, { {"NAME", AsName}, {"DAYTIME", AsDayTime} });
...                             ^^^^   ~~~~~~     ^^^^^^^   ~~~~~~~~~
...                             token  User coded function to replace the token

PageBuilder page("/hello", { header_elem, body_elem, footer_elem });
...
ESP8266WebServer  webServer;  // in ESP8266 case.
page.insert(webServer);
webServer.begin();
...  // 'on' method is no needed.
webServer.handleClient();

http://your.webserver.address/hello will respond as follows.

<html><body>hello <b>My name</b>, <br>Good afternoon.</body></html>

Invoke the HTML assembly

No need in the sketch. It would be invoked from the instance inherited from the WebServer class which corresponding to the platform ESP8266 or ESP32. Also, like the on method of the WebServer class, you need to register the PageBuilder object with the web server object using the insert method.

String func(PageArgument& args);
PageElement element("mold", {{"token", func}})
PageBuilder page("/uri", { element });

ESP8266WebServer server;  // Probably 'WebServer' in ESP32 case.
page.insert(server);    // This is needed.

server.handleClient();  // Invoke from this.

Arguments of invoked user function

Arguments are passed to the function that should be implemented corresponding to tokens. It is the parameter value as GET or POST at the http request occurred like as url?param=value in HTTP GET, and its parameters are stored in PageArgument object and passed to the function as below.

  • HTTP GET with http://xxx.xxx.xxx/?param=value
  • HTTP POST with / HTTP/1.1 Host:xxx.xxx.xxx Connection:keep-alive param=value
String func(PageArgument& args) {
  if (args.hasArg("param"))
    return args.arg("param");
}

PageElement element("hello {{NAME}}.", {{"NAME", func}});

An argument can be accessed with the following method of PageArgument class.

String PageArgument::arg(String name)

Returns the value of the parameter specified by name.

String PageArgument::arg(int i)

Returns the value of the parameter indexed i.

String PageArgument::argName(int i)

Returns parameter name of indexed i.

int PageArgument::args()

Get parameters count of the current http request.

size_t PageArgument::size()

Same as args().

bool PageArgument::hasArg(String name)

Returns whether the name parameter is specified in the current http request.

Declare PageBuilder object and PageElement object

Include directive

#include "PageBuilder.h"

PageBuilder constructor

PageBuilder::PageBuilder();
PageBuilder::PageBuilder(PageElementVT element, HTTPMethod method = HTTP_ANY, TransferEncoding_t chunked = PB_Auto, bool CORS = false);
PageBuilder::PageBuilder(const char* uri, PageElementVT element, HTTPMethod method = HTTP_ANY, TransferEncoding_t chunked = PB_Auto, bool CORS = false);
  • element : PageElement container wrapper. Normally, use the brackets to specify initializer.
    PageElement elem1();
    PageElement elem2();
    PageBuilder page("/", {elem1, elem2});
    
  • method : Enum value of HTTP method as HTTP_ANY, HTTP_GET, HTTP_POST that page should respond.
  • uri : A URI string of the page.
  • chunked : Enumeration type for the transfer-encoding as TransferEncoding_t type. `PB_Aut
View on GitHub
GitHub Stars201
CategoryDevelopment
Updated1mo ago
Forks44

Languages

C++

Security Score

100/100

Audited on Feb 22, 2026

No findings