miko / laravel-latte

Laravel 的 Latte 模板引擎

3.0.4 2024-05-06 15:41 UTC

This package is auto-updated.

Last update: 2024-09-06 16:30:26 UTC


README

通过 Latte 模板引擎扩展 Laravel 框架

安装

$ composer require miko/laravel-latte

然后根据文件扩展名使用模板引擎

配置

将配置文件发布到 config/latte.php

$ php artisan vendor:publish --provider="Miko\LaravelLatte\ServiceProvider"

按照配置文件中的说明操作。

扩展

查看 https://latte.nette.org/tags

和附加

过滤器 nl2br (bool $xhtml = null)

{$text|nl2br}
{$text|nl2br: true}  <!-- xhtml: true -->

默认的渲染为 xhtml 或 html 可以在配置文件中配置。

标签 {link}n:href

类似于 Nette 中的标签,除了控制器和方法之间的分隔符不是 : 而是空格 @,并且默认方法不是 default 而是按照 Laravel 规范的 index。基本上,这是一个简化对 Laravel 的 action() 助手的调用,当不需要写出完整的 FQCN 和单词 Controller 时。此外,可以使用关键字 this 表示当前操作 - 这样就不需要写出未更改的参数。

{link User@detail}             {* shortcut for action([App\Http\Controllers\UserController::class, 'detail']) *}
{link User@}                   {* shortcut for action([App\Http\Controllers\UserController::class, 'index']) *}
{link detail}                  {* shortcut for action([$current_controller, 'detail']) *}
{link User@detail 123, 456}    {* shortcut for action([App\Http\Controllers\UserController::class, 'detail'], [123, 456]) *}
{link User@detail foo => bar}  {* shortcut for action([App\Http\Controllers\UserController::class, 'detail'], ['foo' => 'bar']) *}
{link "Admin\Article@detail"}  {* shortcut for action([App\Http\Controllers\Admin\ArticleController::class, 'detail']) *}
{link this}                    {* generates a link for the current action and current arguments (current URL) *}

{* n tag *}
<a n:href="User@detail 123, foo">

{* Named arguments can be used... *}
<a n:href="Product@show $product->id, lang: cs">product detail</a>
{link Product@show $product->id, lang: cs}

{* ...and (expand) as well because of Latte v2 BC *}
{var $args = [$product->id, lang => cs]}
<a n:href="Product@show (expand) $args">product detail</a>
{link Product@show (expand) $args}

(expand) - 与 ...$arr 运算符等价

this 的使用

路由

Route::get('/users/permissions/{user}/{permission}', [\App\Http\Controllers\UserController::class, 'permissions']);

模板

<a n:href="this sort => date">Sort by date</a>

在地址 mysite.com/users/permissions/1/2 生成链接 mysite.com/users/permissions/1/2?sort=date

标签 {asset}n:src

m 参数添加到 URL 中,参数值为文件最后修改的时间戳。每次文件更改时,都会重新加载,且无需清除浏览器缓存

<script n:src="/js/some-script.js"></script>
<link rel="stylesheet" href="{asset '/css/some-style.css'}">
<img n:src="/imgs/some-image.png">

标签 {csrf}{method}

在表单中生成隐藏的输入 _token_method。请参阅 防止 CSRF 请求表单方法欺骗。渲染为 xhtml 或 html 可以在配置文件中配置。

<form action="/example" method="POST">
    
    {csrf}
    {method PUT}
    
    <!-- Equivalent to... -->
    
    <input type="hidden" name="_token" value="{csrf_token()}" autocomplete="off">
    <input type="hidden" name="_method" value="PUT">
    
</form>

标签 {livewire}{livewireStyles}{livewireScripts}{livewireScriptConfig}

🧪 实验
Livewire 提供的标签。只有当 Livewire 被实现时,它们才可用。

<!doctype html>
<html lang="en">
    <head>
        <title></title>
        {livewireStyles}
    </head>
<body>
    {livewire component-name foo => bar}
    {livewireScripts}
    {livewireScriptConfig}
</body>
</html>

由于 Livewire 自行渲染其模板,因此模板可以是 Latte 或 Blade 文件。

⚠️ 警告:如果组件视图是 Latte 文件,并且默认布局在配置中设置(latte.layout),则组件视图 必须 在开头包含 {layout none}。否则,Latte 引擎将尝试再次为该组件渲染布局。

resources/views/livewire/component-name.latte:

{layout none}
<div>
    ...
</div>

翻译 {_}

Laravel提供了__()trans()函数,分别用于获取翻译字符串,详见获取翻译字符串,以及trans_choice()函数,详见复数化。标签{_}可以处理这两者,它取决于第二个参数,是整数还是数组。

{_'messages.welcome'}
{_'messages.welcome', [name: dayle]}
{_'messages.apples', 10}
{_'time.minutes_ago', 5, [value: 5]}
{_'time.minutes_ago', 5, [value: 5], de}
{_'messages.welcome', locale: de}

上述等同于Laravel函数

echo __('messages.welcome');
echo __('messages.welcome', ['name' => 'dayle']);
echo trans_choice('messages.apples', 10);
echo trans_choice('time.minutes_ago', 5, ['value' => 5]);
echo trans_choice('time.minutes_ago', 5, ['value' => 5], 'de');
echo __('messages.welcome', locale: 'de');

如果您想实现Latte文档中描述的Latte\Essential\TranslatorExtension,可以在ServiceProvider中实现,例如如下所示

use Latte\Essential\TranslatorExtension;
use Miko\LaravelLatte\Runtime\Translator;

public function boot(): void
{
    $latte = $this->app->get(\Latte\Engine::class);
    $latte->addExtension(new TranslatorExtension([Translator::class, 'translate']));
}

为什么默认不实现它呢?

  • {translate}{/translate}n:translate标签使用翻译字符串作为整个段落的键非常诱人,但这样做似乎很糟糕,并可能导致错误率上升。
  • n:translate(版本3.0.13)不起作用
  • 如果使用App::setLocale()在运行时设置语言,则将lang参数作为预编译静态文本的缓存键不起作用

组件{x}

实现Miko\LaravelLatte\IComponent接口的对象可以在模板中被渲染

namespace App\View\Components;

use Illuminate\View\View;
use Miko\LaravelLatte\IComponent;

class Alert implements IComponent
{
    private array $params = [];

    /**
     * Get some services from service container
     */
    public function __construct(private SomeService $someService)
    {
    }

    /**
     * Get variables from template
     */
    public function init(...$params): void
    {
        $this->params = $params;
    }

    /**
     * Get the view / contents that represent the component.
     */
    public function render(): View|string
    {
        return view('components.alert', $this->params);
    }
}

视图

{x alert type => error, message => $message}

组件的根命名空间在配置文件中设置(latte.components_namespace),默认为App\View\Components

⚠️ 警告:如果在配置文件中设置了默认布局(latte.layout),组件视图必须在开头包含{layout none}。否则,Latte引擎将尝试为该组件再次渲染布局。