Add site method to get generate a list of links via a hook.

This commit is contained in:
2026-04-17 04:05:10 +10:00
parent 84f1eda2da
commit 525e5bfb64

View File

@@ -39,6 +39,74 @@ Kirby::plugin(
return $files;
},
/**
* To add this hook to a plugin, replace the foreach filter with any other method to generate the $newLinks[] array.
*
* @version 1.0
*
* Links in the array should have a minimum of the following options set:
* $newLinks[] => [
* "index" => The sort index of the link,
* "url" => The URL of the link,
* "text" => The text of the link,
* "aria" => Accessible version of the link text,
* "active" => True if this is the active link,
* ];
*
* Optional supported options are:
* $newLinks[] = [
* "icon" => An optional Font Awesome icon,
* "disabled" => True if this link should have the 'disabled' HTML attribute,
* "target" => The value of the HTML link target attribute,
* "dropdown" => [
* [
* "divider" => True to display a divider in the dropdown menu,
* ],
* [
* A link, as defined above, that should be displayed in the dropdown menu.
* These links will need to be sorted in the template. Index in this case
* doesn't have any purpose unless you process it in the template.
* ],
* ],
* ];
*/
"hobbyhome.getLinkList" => function ($links = [], $linkLocation = "primary") {
$newLinks = [];
# ---------------------------------------------------------------------------------
# Replace this section with any method of generating the $newLinks[] array.
# ---------------------------------------------------------------------------------
$pages = site()->index(true)->filterBy("linkLocation", $linkLocation);
foreach ($pages as $page) {
if ($page->isDraft() && !($user = kirby()->user() and $user->role()->isAdmin())) {
continue;
}
$newLinks[] = [
"index" => $page->linkIndex()->toInt(),
"url" => $page->url(),
"icon" => ($page->linkIcon()->isNotEmpty()) ? kirbytag("fa", $page->linkIcon()) : "",
"text" => ($page->linkText()->isNotEmpty()) ? $page->linkText() : $page->title(),
"aria" => ($page->linkText()->isNotEmpty()) ? $page->linkText() : $page->title(),
"active" => $page->isActive(),
];
}
# ---------------------------------------------------------------------------------
foreach ($newLinks as $link) {
$index = $link["index"];
# Make sure no other link exists with the current sort order index.
while (isset($links[$index])) {
$index++;
}
$links[$index] = $link;
}
return $links;
},
],
"siteMethods" => [
/**
@@ -62,6 +130,19 @@ Kirby::plugin(
return $files;
},
/**
* Fetch and sort a list of links.
*
* @param string $linkLocation The identifier key for the list of links.
*
* @return Array of links, sorted by index.
*/
"getLinkList" => function ($linkLocation = "primary") {
$links = kirby()->apply("hobbyhome.getLinkList", ["links" => [], "linkLocation" => $linkLocation], "links");
ksort($links, SORT_NUMERIC);
return $links;
},
],
],
info: [