Go模板表达式

huangapple go评论94阅读模式
英文:

Go template expression

问题

{{$Total := 0.00}}
{{ range .Shoes }}
  {{ if .Quantity }}
    {{ $Total := add $Total (mul .Price .Quantity)}}
  {{ end }}
{{ end }}
{{printf "%.2f" $Total}}

函数"add"未定义

总价 * 数量 = 最终价格

英文:
{{$Total := 0.00}}
{{ range .Shoes }}
  {{ if .Quantity }}
    {{ $Total := add $Total (mul .Price .Quantity)}}
  {{ end }}
{{ end }}
{{printf "%.2f" $Total}}

function "add" not defined

Total price * Quantity = Final Price

答案1

得分: 3

package main

import (
	"bytes"
	"fmt"
	"text/template"
)

func add(total, prod float64) float64 {
	return total + prod
}
func mul(quantity, price float64) float64 {
	return quantity * price
}

var funcMap = template.FuncMap{
	"add": add,
	"mul": mul,
}

func main() {
	t := template.Must(template.New("test").Funcs(funcMap).Parse(tmpl))
	var tpl bytes.Buffer
	b := TMPL{
		Total: 0,
		Shoes: []Shoe{
			Shoe{
				Quantity: 5,
				Price:    20,
			},
		},
	}
	err := t.Execute(&tpl, &b)
	if err != nil {
		fmt.Println(err)
	}
	fmt.Println(tpl.String())
}

type TMPL struct {
	Total int
	Shoes []Shoe
}

type Shoe struct {
	Quantity float64
	Price    float64
}

var tmpl = `{{$Total := 0.00}}
{{ range .Shoes }}
  {{ if .Quantity }}
    {{$Total = (add $Total (mul .Price .Quantity))}}
  {{ end }}
{{ end }}
{{printf "%.2f" $Total}}

playground


以上是你提供的代码的翻译结果。

<details>
<summary>英文:</summary>

    
    package main
    
    import (
    	&quot;bytes&quot;
    	&quot;fmt&quot;
    	&quot;text/template&quot;
    )
    
    func add(total, prod float64) float64 {
    	return total + prod
    }
    func mul(quantity, price float64) float64 {
    	return quantity * price
    }
    
    var funcMap = template.FuncMap{
    	&quot;add&quot;: add,
    	&quot;mul&quot;: mul,
    }
    
    func main() {
    	t := template.Must(template.New(&quot;test&quot;).Funcs(funcMap).Parse(tmpl))
    	var tpl bytes.Buffer
    	b := TMPL{
    		Shoes: []Shoe{
    			Shoe{
    				5,
    				20,
    			},
    		},
    	}
    	err := t.Execute(&amp;tpl, &amp;b)
    	if err != nil {
    		fmt.Println(err)
    	}
    	fmt.Println(tpl.String())
    }
    
    type TMPL struct {
    	Total int
    	Shoes []Shoe
    }
    
    type Shoe struct {
    	Quantity float64
    	Price    float64
    }
    
    var tmpl = `{{$Total := 0.00}}
    {{ range .Shoes }}
      {{ if .Quantity }}
        {{ $Total = (add $Total (mul .Price .Quantity))}}
      {{ end }}
    {{ end }}
    {{printf &quot;%.2f&quot; $Total}}


[playground][1]


  [1]: https://go.dev/play/p/RZ_qkM3pyBX

</details>



huangapple
  • 本文由 发表于 2023年2月9日 11:31:29
  • 转载请务必保留本文链接:https://go.coder-hub.com/75393914.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定