mauricius/laravel-htmx

Laravel Htmx 辅助库

v0.6.0 2024-03-19 15:23 UTC

This package is auto-updated.

Last update: 2024-09-19 16:25:59 UTC


README

Laravel 对 htmx 的集成。

Latest Version on Packagist GitHub Tests Action Status Total Downloads

支持的 Laravel 版本 >= v8.80.0。

安装

您可以通过 composer 安装此包

composer require mauricius/laravel-htmx

您可以使用以下命令发布配置文件

php artisan vendor:publish --tag="laravel-htmx"

这是已发布配置文件的内容

return [
];

要安装 htmx,请浏览 其文档

用法

请求

您可以从容器中解析出 HtmxRequest 实例,它提供了读取 htmx 特定 请求头 的快捷方式。

use Mauricius\LaravelHtmx\Http\HtmxRequest;

Route::get('/', function (HtmxRequest $request)
{
    // always true if the request is performed by Htmx
    $request->isHtmxRequest();
    // indicates that the request is via an element using hx-boost
    $request->isBoosted();
    // the current URL of the browser
    $request->getCurrentUrl();
    // true if the request is for history restoration after a miss in the local history cache
    $request->isHistoryRestoreRequest()
    // the user response to an hx-prompt
    $request->getPromptResponse();
    // 	the id of the target element if it exists
    $request->getTarget();
    // the name of the triggered element if it exists
    $request->getTriggerName();
    // the id of the triggered element if it exists
    $request->getTriggerId();
});

响应

  • HtmxResponseClientRedirect

当 htmx 收到带有 HX-Redirect 的响应时,它可以触发客户端重定向。 HtmxResponseClientRedirect 使触发此类重定向变得容易。

use Mauricius\LaravelHtmx\Http\HtmxResponseClientRedirect;

Route::get('/', function (HtmxRequest $request)
{
    return new HtmxResponseClientRedirect('/somewhere-else');
});
  • HtmxResponseClientRefresh

当 htmx 收到带有 HX-Refresh 的响应时,它将触发页面刷新。 HtmxResponseClientRefresh 是一个自定义响应类,允许您发送此类响应。它不接受任何参数,因为 htmx 忽略任何内容。

use Mauricius\LaravelHtmx\Http\HtmxResponseClientRefresh;

Route::get('/', function (HtmxRequest $request)
{
    return new HtmxResponseClientRefresh();
});
  • HtmxResponseStopPolling

当使用 轮询触发器 时,当 htmx 遇到带有特殊 HTTP 状态码 286 的响应时,它将停止轮询。 HtmxResponseStopPolling 是一个具有该状态码的自定义响应类。

use Mauricius\LaravelHtmx\Http\HtmxResponseStopPolling;

Route::get('/', function (HtmxRequest $request)
{
    return new HtmxResponseStopPolling();
});

对于所有剩余的 可用头,您可以使用 HtmxResponse 类。

use Mauricius\LaravelHtmx\Http\HtmxResponse;

Route::get('/', function (HtmxRequest $request)
{
    return with(new HtmxResponse())
        ->location($location) // Allows you to do a client-side redirect that does not do a full page reload
        ->pushUrl($url) // pushes a new url into the history stack
        ->replaceUrl($url) // replaces the current URL in the location bar
        ->reswap($option) // Allows you to specify how the response will be swapped
        ->retarget($selector); // A CSS selector that updates the target of the content update to a different element on the page
});

此外,您还可以使用 addTrigger 方法触发 客户端事件

use Mauricius\LaravelHtmx\Http\HtmxResponse;

Route::get('/', function (HtmxRequest $request)
{
    return with(new HtmxResponse())
        ->addTrigger("myEvent")
        ->addTriggerAfterSettle("myEventAfterSettle")
        ->addTriggerAfterSwap("myEventAfterSwap");
});

如果您想将与事件一起传递的详细信息,可以使用第二个参数发送一个体。它支持字符串或数组。

use Mauricius\LaravelHtmx\Http\HtmxResponse;

Route::get('/', function (HtmxRequest $request)
{
    return with(new HtmxResponse())
        ->addTrigger("showMessage", "Here Is A Message")
        ->addTriggerAfterSettle("showAnotherMessage", [
            "level" => "info",
            "message" => "Here Is A Message"
        ]);
});

如果您想触发多个事件,可以多次调用这些方法。

use Mauricius\LaravelHtmx\Http\HtmxResponse;

Route::get('/', function (HtmxRequest $request)
{
    return with(new HtmxResponse())
        ->addTrigger("event1", "A Message")
        ->addTrigger("event2", "Another message");
});

渲染 Blade 片段

此库还提供基本的 Blade 扩展来渲染 模板片段

库提供了两个新的 Blade 指令:@fragment@endfragment。您可以使用这些指令在模板中指定一个内容块并仅渲染该内容块。例如

{{-- /contacts/detail.blade.php  --}}
<html>
    <body>
        <div hx-target="this">
            @fragment("archive-ui")
                @if($contact->archived)
                    <button hx-patch="/contacts/{{ $contact->id }}/unarchive">Unarchive</button>
                @else
                    <button hx-delete="/contacts/{{ $contact->id }}">Archive</button>
                @endif
            @endfragment
        </div>
        <h3>Contact</h3>
        <p>{{ $contact->email }}</p>
    </body>
</html>

在模板中定义此片段后,我们现在可以渲染整个模板

Route::get('/', function ($id) {
    $contact = Contact::find($id);

    return View::make('contacts.detail', compact('contact'));
});

或者,我们可以通过使用在 \Illuminate\View\View 类中定义的 renderFragment 宏来仅渲染模板的 archive-ui 片段

Route::patch('/contacts/{id}/unarchive', function ($id) {
    $contact = Contact::find($id);

    // The following approaches are equivalent

    // Using the View Facade
    return \Illuminate\Support\Facades\View::renderFragment('contacts.detail', 'archive-ui', compact('contact'));

    // Using the view() helper
    return view()->renderFragment('contacts.detail', 'archive-ui', compact('contact'));

    // Using the HtmxResponse Facade
    return \Mauricius\LaravelHtmx\Facades\HtmxResponse::renderFragment('contacts.detail', 'archive-ui', compact('contact'));

    // Using the HtmxResponse class
    return with(new \Mauricius\LaravelHtmx\Http\HtmxResponse())
        ->renderFragment('contacts.detail', 'archive-ui', compact('contact'));
});

OOB 交换支持

htmx 支持通过返回多个部分响应来更新多个目标,这些响应使用 hx-swap-oop。使用此库,您可以通过使用 HtmxResponse 作为返回类型来返回多个片段。

例如,假设我们想使用 PATCH 请求来标记待办事项为完成,请求地址为 /todos/{id}。通过同样的请求,我们还想在页脚中更新剩余待办事项的数量

{{-- /todos.blade.php  --}}
<html>
    <body>
        <main hx-target="this">
            <section>
                <ul class="todo-list">
                    @fragment("todo")
                        <li id="todo-{{ $todo->id }}" @class(['completed' => $todo->done])>
                            <input
                                type="checkbox"
                                class="toggle"
                                hx-patch="/todos/{{ $todo->id }}"
                                @checked($todo->done)
                                hx-target="#todo-{{ $todo->id }}"
                                hx-swap="outerHTML"
                            />
                            {{ $todo->name }}
                        </li>
                    @endfragment
                </ul>
            </section>
            <footer>
                @fragment("todo-count")
                    <span id="todo-count" hx-swap-oob="true">
                        <strong>{{ $left }} items left</strong>
                    </span>
                @endfragment
            </footer>
        </main>
    </body>
</html>

我们可以使用 HtmxResponse 来返回多个片段

Route::patch('/todos/{id}', function ($id) {
    $todo = Todo::find($id);
    $todo->done = !$todo->done;
    $todo->save();

    $left = Todo::where('done', 0)->count();

    return HtmxResponse::addFragment('todomvc', 'todo', compact('todo'))
        ->addFragment('todomvc', 'todo-count', compact('left'));
});

测试

composer test

变更日志

请参阅变更日志,了解最近有哪些变化。

贡献

请参阅贡献指南,获取详细信息。

安全漏洞

请查阅我们的安全策略,了解如何报告安全漏洞。

致谢

许可证

MIT 许可证 (MIT)。请参阅许可证文件获取更多信息。