Go模板无法与if和range一起正常使用 [英] Go template doesn't work correctly with if and range
本文介绍了Go模板无法与if和range一起正常使用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
https://play.golang.org/p/iQConmYgIN0
PortfolioTemplate
无法正确处理 if
.此 if
制动外部 Range
.该如何解决?
PortfolioTemplate
does not handle if
properly. This if
brakes outer Range
. How to fix this?
推荐答案
使用模板函数可能是一种更好的方法.
Using a template function might be a better way to do this.
在下面的代码示例中,我定义了一个 font
函数,该函数将从 Yield
类型(此示例中提取并移至顶部)确定颜色.
In the following code example, I defined a font
function which would determine the color from a Yield
type (which I extracted and moved to top for this example).
代码示例:
package main
import (
"bytes"
"encoding/json"
"fmt"
"html/template"
)
type Yield struct {
Currency string `json:"currency"`
Value float64 `json:"value"`
}
const portfolioJson = `{
"payload": {
"positions": [
{
"balance": 300,
"expectedYield": {
"currency": "RUB",
"value": 1314
},
"ticker": "SBERP"
},
{
"balance": 4,
"expectedYield": {
"currency": "USD",
"value": -14.87
},
"ticker": "MA"
}
]
}
}`
const PortfolioTemplate = `
<ol>
{{range .Payload.Positions}}
<li>
<strong>{{.Ticker}}</strong> {{.Balance}} (
<font color="{{.ExpectedYield | font }}">
{{.ExpectedYield.Value}}</font> {{.ExpectedYield.Currency}}
)
</li>
{{end}}
</ol>
`
type Portfolio struct {
Payload struct {
Positions []struct {
Ticker string `json:"ticker"`
Balance float64 `json:"balance"`
ExpectedYield Yield `json:"expectedYield"`
}
} `json:"payload"`
}
func (portfolio *Portfolio) Prettify() string {
fontColor := func(y Yield) string {
if y.Value > 0 {
return "green"
}
return "red"
}
t := template.New("Portfolio")
buff := bytes.Buffer{}
tpl := template.Must(t.Funcs(template.FuncMap{"font": fontColor}).Parse(PortfolioTemplate))
_ = tpl.Execute(&buff, portfolio)
return buff.String()
}
func main() {
var portfolio Portfolio
_ = json.Unmarshal([]byte(portfolioJson), &portfolio)
fmt.Println(portfolio.Prettify())
}
输出:
<ol>
<li>
<strong>SBERP</strong> 300 (
<font color="green">
1314</font> RUB
)
</li>
<li>
<strong>MA</strong> 4 (
<font color="red">
-14.87</font> USD
)
</li>
</ol>
这篇关于Go模板无法与if和range一起正常使用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文