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 for tht page

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 a bare shortcode with no arguments nor inner content?

with should be what you look for.

And judging from your first line you probably knew that. Is this not working? Replace the {{ if .Inner }} with a {{ with .Inner }}.

If I replace the {{ if .Inner }} with a {{ with .Inner }} , I get an error:

executing "shortcodes/gallery.html" at <.Inner>: can't evaluate field Inner in type template.HTML

Because inside the with the .Inner is just an . :wink:

{{ with (.Get "dir") }}

{{ else }}
  {{ with .Inner }}
	{{ . }} 
  {{ else }}

  {{ end }}
{{ end }}

Oh…duh. OK. The following always displays “Check 1” for an empty shortcode of {{< gallery >}}:

{{ with (.Get "dir") }}
  <h5>Process Dir</h5>
{{ else }}
  {{ with .Inner }}
    <h5>Check 1</h5>
    {{ . }}
  {{ else }}
    <h5>Check 2</h5>
  {{ end }}
{{ end }}

I’m expecting “Check 2” for an empty shortcode.

Note:

{{< gallery >}}
{{< /gallery >}}

Is NOT empty. It’s a line break. Whitespace is content. You might work through this by using (trim .Inner "\n").

Other than that: post a sample repo so we can look into the issue.

I’m only specifying {{< gallery >}} on a line by itself. There are no open/close shortcodes.

---
front matter
---
This is my gallery.
{{< load-photoswipe >}}
{{< gallery >}}

The above is essentially my test page. There are about a dozen images in the same directory as the page. I’d like to display all the images in that posts directory.

{{ .Inner }} implies that you have at least {{< gallery >}}{{< /gallery >}}, I don’t think you can have shortcodes that close itself AND take .inner codings. So if you want to support {{< gallery >}}something{{< /gallery >}} you will have to have closing tags.

1 Like

That’s it…you have to call it as an empty element - {{< gallery />}}.

Thanks for walking me through this!

This topic was automatically closed 2 days after the last reply. New replies are no longer allowed.