The TemplatePrinter (requires #include <TemplatePrinter.h>) is a template engine that works with any Print object (e.g., PsychicStreamResponse, Serial, File). It allows replacing placeholders in a string with dynamic data.
Parameter Rules:
- Delimiter: Default is
% (e.g., %MY_PARAM%). - Content: Only
a-z, A-Z, 0-9, and _ allowed. - Length: Max 63 characters.
Usage Pattern:
You provide a templateHandler function that is called whenever a parameter is detected. The handler must return true if it handled the parameter, or false if the detected text is not a valid parameter (in which case the text is printed literally).
Example: Templating a response with dynamic heap info:
server.on("/template", [](PsychicRequest *request) {
PsychicStreamResponse response(request, "text/plain");
response.beginSend();
TemplatePrinter printer(response, [](Print &output, const char *param) {
if(strcmp(param, "FREE_HEAP") == 0) {
output.print((double)ESP.getFreeHeap() / 1024.0, 2);
return true;
}
return false;
});
printer.println("Free heap: %FREE_HEAP% Kb");
printer.flush();
return response.endSend();
});
// Function to handle parameter requests.
bool templateHandler(Print &output, const char *param){
if(strcmp(param, "FREE_HEAP") == 0){
output.print((double)ESP.getFreeHeap() / 1024.0, 2);
}else if(strcmp(param, "MIN_FREE_HEAP") == 0){
output.print((double)ESP.getMinFreeHeap() / 1024.0, 2);
}else if(strcmp(param, "MAX_ALLOC_HEAP") == 0){
output.print((double)ESP.getMaxAllocHeap() / 1024.0, 2);
}else if(strcmp(param, "HEAP_SIZE") == 0){
output.print((double)ESP.getHeapSize() / 1024.0, 2);
}else{
return false;
}
output.print("Kb");
return true;
}
// Example serving a request
server.on("/template", [](PsychicRequest *request) {
PsychicStreamResponse response(request, "text/plain");
response.beginSend();
TemplatePrinter printer(response, templateHandler);
printer.println("My ESP has %FREE_HEAP% left. Its lifetime minimum heap is %MIN_FREE_HEAP%.");
printer.println("The maximum allocation size is %MAX_ALLOC_HEAP%, and its total size is %HEAP_SIZE%.");
printer.println("This is an unhandled parameter: %UNHANDLED_PARAM% and this is an invalid param %INVALID PARAM%.");
printer.println("This line finished with %UNFIN");
printer.flush();
return response.endSend();
});