📄 Template Document Builder
This page demonstrates loading an HTML template and modifying it dynamically.
using Astralis;
using Invercargill;
using Invercargill.DataStructures;
using Inversion;
/**
* DocumentBuilderTemplate Example
*
* Demonstrates loading an existing HTML template and modifying elements
* using the DocumentModel classes. Shows how to:
* - Define a MarkupTemplate subclass with embedded HTML
* - Register the template as a singleton with WebApplication
* - Inject and use the template in endpoints
* - Use XPath selectors to find specific elements
* - Modify element content, attributes, and classes
* - Handle form POST to update the document state
*
* This example complements DocumentBuilder.vala by showing template-based
* document manipulation rather than building from scratch.
*
* Usage: document-builder-template [port]
*/
// Application state - a simple counter
class AppState : Object {
public int counter { get; set; }
public int total_changes { get; set; }
public string last_action { get; set; }
public DateTime last_update { get; set; }
public AppState() {
counter = 0;
total_changes = 0;
last_action = "Initialized";
last_update = new DateTime.now_local();
}
public void increment() {
counter++;
total_changes++;
last_action = "Incremented";
last_update = new DateTime.now_local();
}
public void decrement() {
counter--;
total_changes++;
last_action = "Decremented";
last_update = new DateTime.now_local();
}
public void reset() {
counter = 0;
total_changes++;
last_action = "Reset";
last_update = new DateTime.now_local();
}
}
/**
* CounterTemplate - A cached HTML template for the counter page.
*
* This class extends MarkupTemplate to provide a reusable, cached template.
* The HTML is parsed once and cached; new_instance() returns efficient copies.
*/
class CounterTemplate : MarkupTemplate {
///
This page demonstrates loading an HTML template and modifying it dynamically.
The server loads the HTML template and uses XPath selectors to find and modify elements:
// Load the template
var doc = new MarkupDocument.from_string(HTML_TEMPLATE);
// Find and modify elements using XPath
var counter_el = doc.select_one("//div[@id='counter-value']");
counter_el.text_content = counter.to_string();
// Add/remove classes based on state
if (counter > 0) {
counter_el.add_class("status-positive");
}
MarkupDocument.from_string() - Load HTML from templatedoc.select_one(xpath) - Find single element by XPathdoc.select(xpath) - Find multiple elementselement.text_content - Get/set text contentelement.add_class()/remove_class() - Modify CSS classeselement.set_attribute() - Set element attributesdoc.to_result() - Return as HttpResult