feat(examples): cookie auth latte

This commit is contained in:
Jamie Barton 2024-09-06 17:39:46 +01:00
parent a9cd9881cf
commit 3f411ae287
6 changed files with 136 additions and 0 deletions

View File

@ -0,0 +1,27 @@
# Latte Templating Example
This example showcases how to use the Latte templating engine to render views and pass them to Dumbo for displaying as HTML pages.
## Getting Started
Follow these steps to set up and run the example:
1. **Install Dependencies**
First, install the necessary dependencies by running:
```bash
composer install
```
2. **Start the Development Server**
Once the dependencies are installed, start the development server with the following command:
```bash
composer start
```
## Additional Resources
For more information on Latte and its capabilities, visit the official [Latte documentation](https://latte.nette.org/).

View File

@ -0,0 +1,16 @@
{
"require": {
"notrab/dumbo": "@dev",
"latte/latte": "^3.0"
},
"repositories": [
{
"type": "path",
"url": "../../"
}
],
"scripts": {
"start": "php -S localhost:8000 index.php"
},
"prefer-stable": false
}

View File

@ -0,0 +1,56 @@
<?php
require __DIR__ . "/vendor/autoload.php";
use Dumbo\Dumbo;
use Dumbo\Helpers\Cookie;
use Latte\Engine as LatteEngine;
$app = new Dumbo();
$latte = new LatteEngine();
$latte->setAutoRefresh(true);
$latte->setTempDirectory(null);
function render($latte, $view, $params = [])
{
return $latte->renderToString(__DIR__ . "/views/$view.latte", $params);
}
$app->onError(function ($error, $c) {
error_log($error->getMessage());
return $c->json(
[
"error" => "Internal Server Error",
"message" => $error->getMessage(),
"trace" => $error->getTraceAsString(),
],
500
);
});
$app->get("/", function ($c) use ($latte) {
$username = Cookie::getCookie($c, "username");
$html = render($latte, "home", ["username" => $username]);
return $c->html($html);
});
$app->get("/login", function ($c) {
Cookie::setCookie($c, "username", "Dumbo", [
"httpOnly" => true,
"path" => "/",
"maxAge" => 3600,
]);
return $c->redirect("/");
});
$app->get("/logout", function ($c) {
Cookie::deleteCookie($c, "username");
return $c->redirect("/");
});
$app->run();

View File

@ -0,0 +1,17 @@
{layout 'layout.latte'}
{block content}
<h1>
{if $username}
Hello {$username}!
{else}
Hello Guest!
{/if}
</h1>
{if $username}
<p><a href="/logout">Sign Out</a></p>
{else}
<p><a href="/login">Sign In</a></p>
{/if}
{/block}

View File

@ -0,0 +1,11 @@
<!DOCTYPE html>
<html>
<head>
<title>Cookie Auth Latte</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
</head>
<body>
{include content}
</body>
</html>

View File

@ -0,0 +1,9 @@
{layout 'layout.latte'}
{block content}
<h1>Login</h1>
<p>Click the button below to sign in:</p>
<form action="/login" method="get">
<button type="submit">Sign In</button>
</form>
{/block}