0

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}}
eggroll
  • 1,049
  • 9
  • 18
  • 1
    You do not need any special treatment for "inserting" _valid_ URLs. The `html/template` package peforms context-sensitive escaping. If you see `ZgotmplZ` in the output, that means your input was not valid for the context in which you tried to use. – icza Nov 09 '21 at 08:30
  • Thanks @icza for the reply. The issue was that the URLs were of type sql.NullString. So I simply added `.String` to `.ImageHref` and `.ImageSrc`. It works now, even without using the `safeURL` function. Is there a good reason to keep using the `safeURL` function? – eggroll Nov 09 '21 at 19:20
  • 1
    You don't need `safeURL` by default as the template engine does context-sensitive escaping. `safeURL` comes handy when you don't want this automatic escaping. – icza Nov 09 '21 at 19:22
  • @icza That helps, thanks! – eggroll Nov 09 '21 at 22:15

0 Answers0