Breadcrumbs for hierarchical pages

Hi!

I like to structure my pages in an hierarchical way and wanted to see the current nesting / “breadcrumbs”. I added a Template Widget and some space script for it, see below in case anyone else is interested. Happy to hear any comments or suggestions!

---
description: Adds breadcrumbs to pages
tags: template
hooks.top.where: 'true'
---
[[index]] > {{#each getSuperPaths(@page.name)}}[[{{.}}]] > {{/each}}{{getChildPageName(@page.name)}}
Child pages:
{{#if @page.name = "index"}}
```query
page where name =~ "^[^/]+$" render [[Library/Core/Query/Page]]
```
{{else}}
```query
page where name =~ "^" + @page.name + "/[^/]+$" render [[Library/Core/Query/Page]]
```
{{/if}}
```space-script
silverbullet.registerFunction({name: "getSuperPaths"}, (name) => {
  const nameComponents = name.split('/');
  const superPaths = [];
  for (let i = 0; i < nameComponents.length-1; i++) {
    const path = nameComponents.slice(0, i+1).join('/');
    superPaths.push(path);
  }
  return superPaths;
});

silverbullet.registerFunction({name: "getChildPageName"}, (name) => {
  const nameComponents = name.split('/');
  if (nameComponents.length < 1) {
    return "";
  } else {
    return nameComponents.at(-1)
  }
});
```
````
16 Likes

Nice! I ran into the same need and did a similar thing in space-lua before I discovered this solution.
Here it is for reference and comparison:

```space-lua
yg=yg or {}
function yg.breadcrumbs(path)
  local mypage = path or editor.get_current_page()
  local parts = string.split(mypage,"/")
  local crumbs = {}
  for i,part in ipairs(parts) do
    local current = ""
    for j=1,i do
      if current != "" then current=current.."/" end
      current = current..parts[j]
    end
    table.insert(crumbs, {name = current})
  end
  return crumbs
end

yg.t_bc = template.new([==[/[[${name}]]]==])

function yg.bc(path)
  return "[[index|🏠]]"..(template.each(yg.breadcrumbs(path),yg.t_bc)) 
end

(I ran into problems withtable.concat() and unpack(), so the sub-path assembly is loopy)

Usage (should also work in templates/live widgets) :

${yg.bc()}

Raw table:
${yg.breadcrumbs()}

For a different path:
${ yg.bc("Milky Way/Solar System/Earth") }

Will look like that:

1 Like