Skip to content

Instantly share code, notes, and snippets.

@thekid
Created July 29, 2023 11:42
Show Gist options
  • Save thekid/019b12627f129afe7bdaea4cc594b29a to your computer and use it in GitHub Desktop.
Save thekid/019b12627f129afe7bdaea4cc594b29a to your computer and use it in GitHub Desktop.
HTMX and the XP Framework
<?php
use web\Application;
use web\frontend\{Frontend, Handlebars, Get, Post, Delete, Param, View};
class Reactive extends Application {
public function routes() {
$impl= new class() {
private $list= ['One', 'Two'];
#[Get]
public function view() {
return View::named('reactive')->with(['items' => $this->list]);
}
#[Post('/fragment/listing')]
public function add(#[Param] $name) {
$this->list[]= $name;
return View::named('reactive')->fragment('listing')->with(['items' => $this->list]);
}
#[Delete('/fragment/listing')]
public function remove(#[Param] $id) {
unset($this->list[$id]);
return View::named('reactive')->fragment('listing')->with(['items' => $this->list]);
}
};
return new Frontend($impl, new Handlebars('.'));
}
}
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Reactive</title>
<link href="https://fonts.googleapis.com/css2?family=Lato:wght@300&display=swap" rel="stylesheet">
<style type="text/css">
* {
font-family: 'Lato', sans-serif;
}
</style>
</head>
<body>
<h1>Look at this list 😊</h1>
<ul id="list" hx-target="#list">
{{#*fragment "listing"}}
{{#each items}}
<li>{{.}} <button hx-delete="/fragment/listing?id={{@index}}">x</button></li>
{{/each}}
{{/fragment}}
</ul>
<form>
<input type="text" name="name">
<button name="add" hx-post="/fragment/listing" hx-target="#list">Add</button>
</form>
<script src="https://unpkg.com/htmx.org@1.9.4/dist/htmx.min.js"></script>
<script type="module">
// Clear value after entry
const $form = document.forms[0];
$form.elements['add'].addEventListener('click', e => {
setTimeout(() => $form.elements['name'].value = '');
});
</script>
</body>
</html>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment