How to use URLs for image link href and img src with html/template?

I’m trying to use URLs for my href and img src inside my gohtml templates, but I was getting no images (i.e. <img src="#ZgotmplZ" alt="">). So I attempted using template.URL by implementing a SafeURL function, but now I’m basically just getting an empty div for the entire page. The SafeURL function is not being accessed. My other function, IsMultiple, however, is working correctly. What am I doing wrong with the SafeURL function?

var funcMap = template.FuncMap{"isMultiple": IsMultiple, "safeURL": SafeURL}
func IsMultiple(index, divisor int) bool {
	return index%divisor == 0
}

func SafeURL(url string) template.URL {
	return template.URL(url)
}
	pageTemplateMaster := template.New(pageFullName[1])
	_, err := pageTemplateMaster.Funcs(funcMap).ParseFiles(append([]string{pageFullPath}, layoutsFullPaths...)...)
	if err != nil {
		return pageTemplateMaster, err
	}
{{ $carModels := index .Data "carModels" }}
{{ range $i, $carModel := $carModels }}
    {{ if (isMultiple $i 2) }}
        <div class="row gv-3 align-items-center mb-100 mb-lg-0">
			<div class="col-12 col-lg-6 show-on-scroll" data-show-duration="500" data-show-distance="20" data-show-origin="left" data-show-delay="250">
			    <a href="{{.ImageHref|safeURL}}" class="gallery-item gallery-item-lg" data-fancybox="gallery-1" data-animation-effect="fade">
			        <img src="{{.ImageSrc|safeURL}}" alt="">
			    </a>
			</div>
        </div>
    {{else}}
        <div class="row gv-3 align-items-center mb-100 mb-lg-0">
            <div class="col-12 col-lg-6 order-lg-3 show-on-scroll" data-show-duration="500" data-show-distance="20" data-show-origin="right" data-show-delay="250">
                <a href="{{.ImageHref|safeURL}}" class="gallery-item gallery-item-lg" data-fancybox="gallery-1" data-animation-effect="fade">
                    <img src="{{.ImageSrc|safeURL}}" alt="">
                </a>
            </div>
        </div>
    {{end}}

Hi @app-o-matix,

SafeURL() does not seem to be the culprit, it works well in this test code.

Can you trim down your code to a minimal example that still produces the unexpected result?

@christophberger Thanks for the response. I figured out what the issue was. The URLs were being passed to the template as sql.NullString rather than string. So, the solution was simply to change .ImageHref and .ImageSrc to .ImageHref.String and .ImageSrc.String. It works without using safeURL so I don’t know if there is any reason to keep it.

Ooh now that’s a subtle error. Glad to hear you discovered and fixed it.

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