templates in html

73 views
Skip to first unread message

Денис Мухортов

unread,
Oct 26, 2021, 3:23:23 AM10/26/21
to golang-nuts
I need to pass data from the map[string]interface{} through the template
I dont know why, but I catch the error:
template: stone-card.html:2: function "stoneShop" not defined.
Code in go:
files := []string{
                dirWithHTML + "index.html",
                dirWithHTML + "stone-card.html",
            }
            tmp, err := template.ParseFiles(files...)
            if err != nil {
                fmt.Println(err)
            }
            err = tmp.Execute(w, block)
            if err != nil {
                log.Fatal(err)
            }
            stoneShop := stones()
            err = tmp.ExecuteTemplate(w, "stone", stoneShop)
            // var stoneShop map[string]interface{}
            if err != nil {
                log.Print(err)
            }
Template Code:
{{define "stone"}}
{{range $key, $value := stoneShop}}
<li class="card {{$value.Rare}}">
    <div class="side1">
      <img class="card__img" src={{$value.URL}} alt="{{$value.Name}}">
    </div>
    <div class="side2">
      <h3 class="card__name">
        {{$value.Name}}
      </h3>
      <p class="card__desc">
        {{$value.Description}}
      </p>
      <div class="card__rare">
        {{$value.Rare}}
      </div>
      <div class="buy">
        <button class="btn btn-reset">Купить</button>
        <div class="item-price">{{$value.Price}} C</div>
      </div>
    </div>
</li>
{{end}}
{{end}}

Marcin Romaszewicz

unread,
Oct 26, 2021, 11:33:01 AM10/26/21
to Денис Мухортов, golang-nuts
Have a look at this:

You need to provide a map of function names to function references to the template engine, otherwise, it has no idea what "stoneShop" is, because all it sees is an interface{} and has no context to know that it's a function. This data argument is explored via reflection, so if you reference ".Something", the template engine will look in data for a field with that name.

The function map that I linked above is where you would provide your "stoneShop" function.

--
You received this message because you are subscribed to the Google Groups "golang-nuts" group.
To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/2edfe28a-d136-43a4-819e-081644d1683cn%40googlegroups.com.

Денис Мухортов

unread,
Oct 26, 2021, 1:22:04 PM10/26/21
to Marcin Romaszewicz, golang-nuts
Thanks

вт, 26 окт. 2021 г. в 18:32, Marcin Romaszewicz <mar...@gmail.com>:
Reply all
Reply to author
Forward
0 new messages