I couldn’t find anything online, but I’m wondering how I could loop through all occurrences of a certain shortcode in a markdown file and access it’s “.Inner” content to display it in my HTML. I’m not quite sure how I would solve this.
So I want to access the content of all “title” shortcodes in a loop, so I can build a list out of it in my single.html file for example:
Some text. This shouldn't be considered.
{< title >}
This is a title.
{< /title >}
Something else. This shouldn't be considered of course.
{< title >}
Another title
{< /title >}
Thank you already in advance, the support here is awesome!
You can’t really access the shortcode in single.html as far as I know.
While looping through all shortcodes is probably not possible, what you can do instead is just create one shortcode and add all the values as parameters to it. Then you can use it (untested):
{{< capture >}}
Frankly, my dear, I don't _give_ a damn.
{{< /capture >}}
{{< capture show >}}
Toto, I've a _feeling_ we're not in **Kansas** anymore.
{{< /capture >}}
{{< capture hide >}}
I'm gonna make him an **offer** he can't refuse.
{{< /capture >}}
layouts/shortcodes/capture.html
{{- $show := false -}}
{{- with .Get 0 -}}
{{- if eq . "show" -}}
{{- $show = true -}}
{{- else if eq . "hide" -}}
{{- $show = false -}}
{{- else -}}
{{- errorf "The %s shortcode accepts a single positional parameter with a value of either 'show' or 'hide'. See %s" $.Name $.Position -}}
{{- end -}}
{{- end -}}
{{- with .Inner -}}
{{- $.Page.Scratch.SetInMap $.Name (printf "%04d" $.Ordinal) . -}}
{{- if $show -}}
{{- . | $.Page.RenderString (dict "display" "block") -}}
{{- end -}}
{{- else -}}
{{- errorf "The %s shortcode requires 'Inner' content. See %s" .Name .Position -}}
{{- end -}}
There is one last thing I wanted to mention though. Everything worked fine, until I added a new shortcode with content. It is at the very bottom of the markdown file, but in the ordered list, it’s at the second place, right below the first entry. I expect it to be added as the last element of the list.
Sorry about that. With 11 or more captures the sorting failed due to alphabetical instead of numeric sorting. I’ve revised my earlier post with two changes:
This concerns me. I understand why it would have happened with 11 or more, but it should not have happened with only 4. Please let me know if you are able to reproduce the problem.