Go模板无法与if和range一起正常使用

时间:2019-10-06 11:16:31

标签: templates go

https://play.golang.org/p/iQConmYgIN0

PortfolioTemplate无法正确处理if。该if制动外部Range。该如何解决?

2 个答案:

答案 0 :(得分:1)

使用模板功能可能是一种更好的方法。

在下面的代码示例中,我定义了一个2019-10-06 12:50:11 [rotating_proxies.expire] DEBUG: Proxy <http://197.254.16.30:8080> is DEAD 2019-10-06 12:50:11 [rotating_proxies.middlewares] DEBUG: Retrying <GET https://www.gulahmedshop.com/khadi-net-3-pc-outfit-glamour-19-48> with another proxy (failed 3 times, max retries: 5) 2019-10-06 12:50:12 [rotating_proxies.expire] DEBUG: Proxy <http://181.30.95.162:33078> is GOOD 2019-10-06 12:50:12 [scrapy.core.engine] DEBUG: Crawled (200) <GET https://www.gulahmedshop.com/gls-18-143> (referer: https://www.gulahmedshop.com/women?cat=399&price=-3000) 2019-10-06 12:50:12 [scrapy.core.scraper] DEBUG: Scraped from <200 https://www.gulahmedshop.com/gls-18-143> {'Image Url': u'https://d224nth7ac0evy.cloudfront.net/catalog/product/cache/1e8ef93b9b4867ab9f3538dde2cb3b8a/g/l/gls-18-143_1_.jpg', 'Price': u'PKR 2,058', 'Category Name': u'and above', 'Product Title': u'GLS-18-143', 'Prouct page': 'https://www.gulahmedshop.com/gls-18-143'} 2019-10-06 12:50:12 [rotating_proxies.expire] DEBUG: Proxy <http://171.239.46.185:8080> is DEAD 2019-10-06 12:50:12 [rotating_proxies.middlewares] DEBUG: Retrying <GET https://www.gulahmedshop.com/gls-18-230> with another proxy (failed 2 times, max retries: 5) 函数,该函数将从font类型(在此示例中提取并移至顶部)确定颜色。

代码示例:

Yield

输出:

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())
}

答案 1 :(得分:1)

相比之下,将0替换为0.0很有帮助。