|
| 1 | +== HTMX |
| 2 | + |
| 3 | +https://htmx.org[HTMX] first-class support for Jooby. |
| 4 | + |
| 5 | +The HTMX module provides a seamless bridge between modern, reactive Single Page Application (SPA) mechanics and traditional server-side rendering. It offers both a memory-safe Imperative Builder and a powerful Declarative Annotation API (via APT) to orchestrate HTMX responses without repetitive boilerplate. |
| 6 | + |
| 7 | +*Note:* `HtmxTemplateEngine` acts as a composite delegator. You must also install a backing template engine (like Handlebars, Freemarker, or Pebble) to actually render the views. |
| 8 | + |
| 9 | +=== Usage |
| 10 | + |
| 11 | +1) Add the dependencies (HTMX and your preferred template engine): |
| 12 | + |
| 13 | +[dependency, artifactId="jooby-htmx, jooby-handlebars:Handlebars Module"] |
| 14 | +. |
| 15 | + |
| 16 | +2) Write your templates inside the `views` folder. Notice how the layout dynamically embeds the requested partial using `childView`. |
| 17 | + |
| 18 | +.views/layout.hbs |
| 19 | +[source, html] |
| 20 | +---- |
| 21 | +<!DOCTYPE html> |
| 22 | +<html> |
| 23 | +<body> |
| 24 | + <nav>My App</nav> |
| 25 | + <main> |
| 26 | + {{> (lookup childView) }} |
| 27 | + </main> |
| 28 | +</body> |
| 29 | +</html> |
| 30 | +---- |
| 31 | + |
| 32 | +.views/tasks.hbs |
| 33 | +[source, html] |
| 34 | +---- |
| 35 | +<ul id="task-list"> |
| 36 | + {{#each tasks}} |
| 37 | + <li>{{title}}</li> |
| 38 | + {{/each}} |
| 39 | +</ul> |
| 40 | +---- |
| 41 | + |
| 42 | +3) Install the module and write your controller. |
| 43 | + |
| 44 | +.Java |
| 45 | +[source, java, role="primary"] |
| 46 | +---- |
| 47 | +import io.jooby.htmx.HtmxModule; |
| 48 | +import io.jooby.handlebars.HandlebarsModule; |
| 49 | +import io.jooby.annotation.htmx.HxView; |
| 50 | +
|
| 51 | +{ |
| 52 | + install(new HandlebarsModule()); <1> |
| 53 | + install(new HtmxModule()); <2> |
| 54 | +
|
| 55 | + mvc(new TaskUIHtmx_()); <3> |
| 56 | +} |
| 57 | +
|
| 58 | +public class TaskUI { |
| 59 | + |
| 60 | + @GET("/tasks") |
| 61 | + @HxView(value = "tasks.hbs", layout = "layout.hbs") |
| 62 | + public Map<String, Object> getTasks() { |
| 63 | + return Map.of("tasks", List.of(new Task("Buy milk"))); |
| 64 | + } |
| 65 | +} |
| 66 | +---- |
| 67 | + |
| 68 | +.Kotlin |
| 69 | +[source, kt, role="secondary"] |
| 70 | +---- |
| 71 | +import io.jooby.htmx.HtmxModule |
| 72 | +import io.jooby.handlebars.HandlebarsModule |
| 73 | +import io.jooby.annotation.htmx.HxView |
| 74 | +
|
| 75 | +{ |
| 76 | + install(HandlebarsModule()) <1> |
| 77 | + install(HtmxModule()) <2> |
| 78 | +
|
| 79 | + mvc(TaskUIHtmx_()) <3> |
| 80 | +} |
| 81 | +
|
| 82 | +class TaskUI { |
| 83 | + |
| 84 | + @GET("/tasks") |
| 85 | + @HxView(value = "tasks.hbs", layout = "layout.hbs") |
| 86 | + fun getTasks(): Map<String, Any> { |
| 87 | + return mapOf("tasks" to listOf(Task("Buy milk"))) |
| 88 | + } |
| 89 | +} |
| 90 | +---- |
| 91 | + |
| 92 | +<1> Install your base template engine |
| 93 | +<2> Install the HTMX engine |
| 94 | +<3> Add generated `Htmx_` controller |
| 95 | + |
| 96 | +=== The SPA Shell Layout Engine |
| 97 | + |
| 98 | +The `@HxView` annotation implements a secure, Fail-Fast Guard Clause for layout management. |
| 99 | + |
| 100 | +When you define a `layout` attribute, the framework intelligently checks the origin of the request: |
| 101 | + |
| 102 | +* **HTMX AJAX Requests:** The layout is ignored. The framework responds only with the fast, targeted partial view (`tasks.hbs`). |
| 103 | +* **Direct Browser Requests (F5 / Bookmarks):** The framework intercepts the request, blocks the raw fragment from rendering, and automatically injects the partial inside your defined `layout.hbs` (passed as the `childView` attribute). |
| 104 | + |
| 105 | +If a method returns a dynamic HTMX fragment but *lacks* a layout, direct browser access is automatically blocked via a `406 Not Acceptable` exception. |
| 106 | + |
| 107 | +=== Declarative API (Annotations) |
| 108 | + |
| 109 | +When using Jooby's MVC routes, you can orchestrate complex UI state entirely through annotations: |
| 110 | + |
| 111 | +.Java |
| 112 | +[source, java] |
| 113 | +---- |
| 114 | +@POST("/tasks") |
| 115 | +@HxView("task_row.hbs") |
| 116 | +@HxOob("task_counter.hbs") // Automatically appends an Out-Of-Band swap |
| 117 | +@HxTrigger("taskAdded") // Triggers a client-side JS event |
| 118 | +@HxError("task_error.hbs") // Scoped Error Handler: Catches validation errors |
| 119 | +public Task addTask(@Valid TaskDto dto) { |
| 120 | + return db.save(dto); |
| 121 | +} |
| 122 | +---- |
| 123 | + |
| 124 | +==== Scoped Error Handling & Validation |
| 125 | +The `@HxError` annotation acts as a "UI Janitor" for **Scoped Errors** (such as HTTP 400 Bad Request or 422 Unprocessable Entity). If Bean Validation fails, it catches the exception and renders your targeted error template. |
| 126 | + |
| 127 | +* **Validation Integration:** The model passed to your error template automatically includes a `validationResult` object that perfectly follows the `io.jooby.validation.ValidationResult` format. This allows seamless integration with Jooby's Jakarta validation modules (`hibernate-validator` or `avaje-validator`). |
| 128 | +* **Auto-Clearing:** Crucially, on a *successful* request, the framework automatically appends an empty OOB swap for the error template, instantly clearing the UI of any previous error messages. |
| 129 | + |
| 130 | +=== Imperative API (HtmxResponse) |
| 131 | + |
| 132 | +For scenarios lacking a primary view (like a `DELETE` operation), use the fluent `HtmxResponse` builder to explicitly chain events, headers, and OOB updates. |
| 133 | + |
| 134 | +.Java |
| 135 | +[source, java, role="primary"] |
| 136 | +---- |
| 137 | +@DELETE("/tasks/{id}") |
| 138 | +public HtmxResponse deleteTask(@PathParam String id) { |
| 139 | + db.delete(id); |
| 140 | + |
| 141 | + return HtmxResponse.empty() |
| 142 | + .addOob("task_counter.hbs", Map.of("activeCount", db.getActiveCount())) |
| 143 | + .triggerAfterSettle("showToast", Map.of("message", "Task deleted!")); |
| 144 | +} |
| 145 | +---- |
| 146 | + |
| 147 | +.Kotlin |
| 148 | +[source, kt, role="secondary"] |
| 149 | +---- |
| 150 | +@DELETE("/tasks/{id}") |
| 151 | +fun deleteTask(@PathParam id: String): HtmxResponse { |
| 152 | + db.delete(id) |
| 153 | + |
| 154 | + return HtmxResponse.empty() |
| 155 | + .addOob("task_counter.hbs", mapOf("activeCount" to db.getActiveCount())) |
| 156 | + .triggerAfterSettle("showToast", mapOf("message" to "Task deleted!")) |
| 157 | +} |
| 158 | +---- |
| 159 | + |
| 160 | +=== Global Error Handling |
| 161 | + |
| 162 | +While `@HxError` handles scoped validation, you can seamlessly convert **Global Application Errors** (like 500 Server Crashes) into graceful HTMX responses (like OOB toast notifications) by passing a custom `HtmxErrorHandler` to the module during installation. |
| 163 | + |
| 164 | +**Smart Interception:** This global handler is highly intelligent. It *only* intercepts requests that contain the `HX-Request: true` header. If a standard browser request crashes (e.g., a normal page load or hitting F5), this handler is safely bypassed, and the default Jooby global application error handler takes over to display a standard error page. |
| 165 | + |
| 166 | +.Java |
| 167 | +[source, java, role="primary"] |
| 168 | +---- |
| 169 | +import io.jooby.htmx.HtmxModule; |
| 170 | +
|
| 171 | +{ |
| 172 | + install(new HtmxModule((ctx, cause, code) -> { |
| 173 | + // Convert the crash into a safe UI notification without breaking the DOM |
| 174 | + return HtmxResponse.empty(code) |
| 175 | + .addOob("toast.hbs", Map.of("error", cause.getMessage())); |
| 176 | + })); |
| 177 | +} |
| 178 | +---- |
| 179 | + |
| 180 | +.Kotlin |
| 181 | +[source, kt, role="secondary"] |
| 182 | +---- |
| 183 | +import io.jooby.htmx.HtmxModule |
| 184 | +
|
| 185 | +{ |
| 186 | + install(HtmxModule { ctx, cause, code -> |
| 187 | + HtmxResponse.empty(code) |
| 188 | + .addOob("toast.hbs", mapOf("error" to cause.message)) |
| 189 | + }) |
| 190 | +} |
| 191 | +---- |
0 commit comments