How to get calling page's context in a shortcode to place a submenu?


#1

I have a shortcode “putsubmenu” that I want to use to put a specific menu:

<div class="buttons">
  <a class="button" href="/maintopic"><span class="icon"><i class="fas fa-anchor"></i></span></a>
 
{{ $currentPage := (.Get 0) }}
{{ range $.Site.Menus.mainsub }}
  <a class="button{{ if $currentPage.IsMenuCurrent "mainsub" . }} is-active{{ end }}" href="{{ .URL }}">{{ .Name }}</a>
{{ end }}

</div>

Then in markdown files, I specify they are a member of the “mainsub” menu in frontmatter:

menu:
  mainsub:
    Name: Some subtopic page
    Weight: 10
    Url: /maintopic-subtopic1

… and in the markdown body, specify the shortcode like:

 {{< putsubmenu >}}

In the code I’m trying to get the current page to highlight with:

{{ if $currentPage.IsMenuCurrent "mainsub" . }} is-active{{ end }}

… but, the is-active class never gets set. This is likely a context issue, related to the fact that this is in a shortcode, but I’ve tried a bunch of variations in the meat of the range loop but, nothing is causing that class to get added.

The menu does work and appears on the page I add the above shortcode to, assuming the page has the menu added to the frontmatter.

Any advice appreciated, thanks!


#2

Have you tried setting $currentPage in the template that contains the shortcode? Not sure if that would give it context?


#3

In this case, that would be the single. I think the “context” simply exists and I don’t know exactly how to manipulate it. I might be able to specify what I need as args in the shortcode though, and use those for comparison…


#4

To get the context of the calling page, it’s $.Page that’s needed.

 {{ $currentPage := $.Page }}
  ...etc

The .Get 0 I originally had is obviously a mistake, since that is grabbing arguments of the shortcode. Oops.