From 23504ea077e7abe0bb54a9d041d2ca41b8ab2378 Mon Sep 17 00:00:00 2001 From: Johann Schopplich Date: Mon, 9 Oct 2023 17:34:22 +0200 Subject: [PATCH] feat: `writerResolver.pathPrefix` config option --- README.md | 12 ++++++++++++ src/extensions/fieldMethods.php | 10 ++++++++-- 2 files changed, 20 insertions(+), 2 deletions(-) diff --git a/README.md b/README.md index c262bce..caac8cd 100755 --- a/README.md +++ b/README.md @@ -252,6 +252,18 @@ return [ This field method resolves page and file permalinks to their respective URLs. It's primarily intended for usage with KQL queries, because the value of `writer` fields contain permalink URLs like `/@/page/nDvVIAwDBph4uOpm`. +In multilanguage setups, you may want to add a prefix to the URL, e.g. `/en` or `/de`. You can do so by defining a custom `writerResolver.pathPrefix` option in your `config.php`: + +```php +# /site/config/config.php +return [ + 'writerResolver' => [ + // Add the language code as a prefix to the URL + 'pathPrefix' => fn (\Kirby\Cms\App $kirby) => '/' . $kirby->language()->code() + ] +]; +``` + ### `toResolvedBlocks()` The `toResolvedBlocks()` method is a wrapper around the `toBlocks()` method. It's primarily intended for usage with KQL queries, because the `toBlocks()` method returns only UUIDs for the `files` and `pages` fields. diff --git a/src/extensions/fieldMethods.php b/src/extensions/fieldMethods.php index bb61ed8..623574c 100644 --- a/src/extensions/fieldMethods.php +++ b/src/extensions/fieldMethods.php @@ -143,16 +143,22 @@ * @kql-allowed */ 'toResolvedWriter' => function (\Kirby\Content\Field $field) { + $kirby = $field->parent()->kirby(); + $prefixFn = $kirby->option('writerResolver.pathPrefix'); + $prefix = $prefixFn + ? (is_callable($prefixFn) ? $prefixFn($kirby) : $prefixFn) + : ''; + return preg_replace_callback( '!href="\/@\/(page|file)\/([^"]+)"!', - function ($matches) { + function ($matches) use ($prefix) { $type = $matches[1]; // Either `page` or `file` $id = $matches[2]; // The UUID // Resolve the UUID to the actual model URL if ($model = \Kirby\Uuid\Uuid::for($type . '://' . $id)?->model(true)) { $parsedUrl = parse_url($model->url()); - return 'href="' . ($parsedUrl['path'] ?? '/') . '"'; + return 'href="' . $prefix . ($parsedUrl['path'] ?? '/') . '"'; } // If not resolvable, return the original match