bilbofox / latte-asset-extension
Latte v3 扩展,添加 n:asset 宏以简化 Latte 中的资源渲染
Requires
- php: >=8.0.0
- latte/latte: ^3
This package is not auto-updated.
Last update: 2024-09-21 17:09:12 UTC
README
Latte v3 扩展,添加 n:asset
宏以简化资源渲染(主要针对 css/js 文件)
使用宏很简单,我们只需将属性 n:asset
或 n:src
添加到常用 HTML 标签 <link>
或 <script>
或 <img>
。宏会自动生成链接资源 URL 的主参数,如 <script src="...">
,并根据需要添加其他参数 - 例如,如果链接 CSS 样式的参数 rel=""
已存在,它将尊重该参数。除非链接的 URL 是绝对路径,否则它将使用 {$basePath}
变量作为生成路径的前缀。
例如,当我们在 Latte 中使用它时
<script n:asset="node_modules/jquery/dist/jquery.min.js"></script> <link n:asset="node_modules/@fortawesome/fontawesome-free/css/all.css">
输出看起来像这样
<script type="text/javascript" src="/my/base/path/node_modules/jquery/dist/jquery.min.js"></script> <link rel="stylesheet" type="text/css" href="/my/base/path/node_modules/@fortawesome/fontawesome-free/css/all.css">
通过使用 Latte Neon DI 扩展来注册很简单
latte: extensions: Bilbofox\Latte\AssetExtension
格式化程序
此扩展的主要目的是格式化程序 - 可以进一步操作资源的最终渲染。
格式化程序是任何通过调用注册到扩展的可调用对象。
$assetExtension = new Bilbofox\Latte\AssetExtension; $assetExtension->addFormatter(function (string $path): string { // ... return $path; });
回调接收原始路径作为参数,并可以在内部修改它。
库包含以可调用类形式存在的现有格式化程序。
Bilbofox\Latte\Formatters\VersionFormatter(int|string|callable $version)
将版本添加到资源中,形式为查询参数 ?v=
在末尾。
版本可以是数字、字符串或接收原始路径的可调用对象。
Bilbofox\Latte\Formatters\FileVersionFormatter(string $wwwDir)
是先前格式化程序的扩展,它使用资源文件的最后修改时间戳作为版本 - 当新资源文件部署到生产服务器时非常有用 - 强制客户端重新加载浏览器缓存的资源。
这里我们注册扩展与文件版本格式化程序
latte: extensions: - @latteAssetExtension latteAssetExtension: class: Bilbofox\Latte\AssetExtension setup: - addFormatter(Bilbofox\Latte\Formatters\FileVersionFormatter(%wwwDir%))
当我们然后在 Latte 中使用它时
<script n:asset="node_modules/jquery/dist/jquery.min.js"></script>
我们得到类似这样的结果
<script type="text/javascript" src="/my/base/path/node_modules/jquery/dist/jquery.min.js?v=1708647873"></script>