Skip to content

Commit

Permalink
feat: writerResolver.pathPrefix config option
Browse files Browse the repository at this point in the history
  • Loading branch information
johannschopplich committed Oct 9, 2023
1 parent 3d45a7e commit 23504ea
Show file tree
Hide file tree
Showing 2 changed files with 20 additions and 2 deletions.
12 changes: 12 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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.
Expand Down
10 changes: 8 additions & 2 deletions src/extensions/fieldMethods.php
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down

0 comments on commit 23504ea

Please sign in to comment.