Search code examples
hugohugo-shortcode

How to check if .Inner is empty


I am trying to write a {{< gallery >}} shortcode that will either generate a gallery with all the images in a directory you define, the contents you define via .Inner, or simply all the image resources related to the page. Here are the forms I'm trying to support:

  1. {{< gallery dir="/gallery/alaska/" />}} - specified directory
  2. {{< gallery >}} {{< figure src="image1.jpg" >}} {{< /gallery >}} - specified inner content
  3. {{< gallery >}} - use all the image resources

I can process the first two, but it is not clear to me how to determine if there nothing in the .Inner variable so I can process form 3 above. I would expect to do something like the following:

{{- with (.Get "dir") -}}
  // do stuff with the specified directory (works fine)
{{- else -}}
  {{- if .Inner }}
    {{ .Inner }} // Always executes
  {{- else -}}
    // do stuff related to resources in this page
  {{- end }}
{{- end }}

How do I detect the bare shortcode with no arguments nor inner content?


Solution

  • The key to making this work is to use an empty tag in the form of <tag/> so that there is inner content but it is empty.

    This means the following code works if you use {{< gallery />}} as your shortcode:

    {{ with (.Get "dir") }}
      // do stuff with the directory
    {{ else }}
      {{ with .Inner }}
        {{ . }}
      {{ else }}
        // do stuff related to this page
      {{ end }}
    {{ end }}