Views
=====
In the Model–View–Controller pattern, a **View** is responsible for presentation—the HTML, emails or other templates that your users see. Even in an API-first framework, simple server-side views can be useful for emails, status pages or admin panels.
LacePHP provides a lightweight PHP-based templating helper so you can keep your display logic separate from your controller logic.
Helper Function
---------------
Use the global `view()` function anywhere to render a PHP template into a string:
.. code-block:: php
// weave/Views/emails/welcome.php
Welcome, = htmlspecialchars($name, ENT_QUOTES, 'UTF-8') ?>!
Thank you for joining LacePHP.
// In your controller or route:
echo view('emails.welcome', ['name' => 'Alice']);
**How it works**
1. You call `view('emails.welcome', $data)`.
2. LacePHP converts dots to directory separators and looks first in your app folder (`weave/Views/emails/welcome.php`), then falls back to the framework’s `shoebox/views` folder.
3. It `extract()`s your `$data` into local variables, includes the file, and returns the buffered output.
Basic Usage
-----------
.. code-block:: php
// 1. Create the template file
// File: weave/Views/articles/show.php
= htmlspecialchars($title, ENT_QUOTES) ?>
= nl2br(htmlspecialchars($body, ENT_QUOTES)) ?>
// 2. Render in your controller
class ArticleController
{
public function show(array $params)
{
$article = Article::find($params['id']);
if (! $article) {
return kickback()->notFound('Article not found');
}
// Pass attributes to the template
return view('articles.show', [
'title' => $article->title,
'body' => $article->body,
]);
}
}
Fallback Views
--------------
If you do not override a template in `weave/Views`, LacePHP will use the default in `shoebox/views`. This lets you customise only the views you need while still shipping sensible defaults.
Best Practices
--------------
- **Keep logic out of views**
Only display data—fetching or transforming data belongs in controllers or services.
- **Escape all output**
Use `htmlspecialchars()` or equivalent to prevent cross-site scripting (XSS).
- **Use small, focused templates**
Split large pages into includes (e.g. headers, footers, partials) for maintainability.
- **Name templates clearly**
Follow the dot notation to match folder structure:
`view('users.profile.edit')` → `weave/Views/users/profile/edit.php`.
.. warning::
- If a template file is missing, `view()` throws a `RuntimeException`—catch it or ensure your file paths are correct.
- Avoid heavy loops or database calls inside templates; prepare all data before calling `view()`.
By using `view()`, you can cleanly separate presentation from business logic, making templates easy to read, maintain and secure.
|
|