Passing variables between function contexts?

I’m trying to create a theme with lots of customization available in config.toml, and I’m running into a problem with cascading multiple selections. In this example, I’d like to offer them the option to create a “hero” image on their subpages (anything that isn’t a home-page). If they want a hero image, they can then select to blur it.

The problem is that the image resource is lost when trying to reference the processed resource.

The below code has two “img src” tags. If config.toml has subPageHeroImage defined and subPageHeroBlur = true, then I would expect both those images to be blurred. However, they are not.

What it seems like is I’m creating another $hero variable in the {{ with }} context. If so, how do I access that from or pass it back to the outside context? Or how do I perform the filter operations in the parent context?

Edit: I’m aware I can use an “else” for this specific example, but that doesn’t help if I need another selectable filter or if I want to reuse the result later in the template.

{{ with $hero := resources.GetMatch .Site.Params.subPageHeroImage }} 
    {{ with $.Site.Params.subPageHeroBlur }}
        {{ if . }}
            {{ $hero := $hero | images.Filter (images.GaussianBlur 8) }} 

            <!-- This renders blurred as expected. -->
            <img src="{{ $hero.RelPermalink }}" height="300px"> 

        {{ end }}
    {{ end }}

    <!-- this renders $hero, but not blurred. How do I reference the blurred version from this context? -->
    <img src="{{ $hero.RelPermalink }}" height="300px"> 

{{ end }}

You are re-initializing $hero within the if block. Use = instead.

2 Likes

Ha, well it was just that simple, and answers one of those other questions I’ve been meaning to look up, having never used Go before. (what’s the := mean)

Thanks!

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