text / html模板包中的“范围”操作和“管道”说明。 Golang

时间:2015-01-15 21:03:52

标签: templates go pipeline

我尝试在text / html模板包中获得一些优点。我从golang网站上读过它的文档。很难理解究竟是什么意思。 (点)一般而且在范围动作的某个时间。究竟是什么意思"管道",也许它很难理解,因为我的英语不是母语):

{{pipeline}}
The default textual representation of the value of the pipeline
is copied to the output.

让我们考虑一个例子:

    data := map[string]interface{}{
        "struct": &Order{
            ID:     1,
            CustID: 2,
            Total:  3.65,
            Name: "Something",
        },
        "name1":  "Timur",
        "name2": "Renat",
    }
    t.ExecuteTemplate(rw, "index", data)

这是"索引":

{{define "index"}}
    {{range $x := .}}
        {{.}}
        <b>{{$x}}</b><br>
        <i>{{$.struct.ID}}</i><br>
        <br>
        # the lines below don't work and break the loop
        # {{.ID}}
        # or
        # {{.struct.ID}}

        # what if I want here another range loop that handles "struct" members
        # when I reach "struct" field in the data variable or just do nothing
        # and just continue the loop? 
    {{end}}
{{end}}

输出:

铁木尔
铁木尔
1

长Renat
长Renat
1

{1 2 3.65 Something}
{1 2 3.65 Something}
1

1 个答案:

答案 0 :(得分:5)

管道

模板包中的管道指的是您在命令行中执行的相同类型的“管道”。

例如,这是在Mac上为您的NIC分配默认网关的一种方法:

route -n get default | grep 'gateway' | awk '{print $2}'

基本上,route -n get default首先运行。管道字符|表示“取出route命令的输出,并将其推送到grep命令”,而不是将结果打印到控制台。此时,grep 'gateway'会在从route收到的输入上运行。然后将grep的输出推送到awk。最后,由于没有更多的管道,您在屏幕上看到的唯一输出是awk想要打印的内容。

在模板包中有点相同。您可以将值传递给方法调用并将它们链接在一起。如:

{{ "Hello world!" | printf "%s" }}

相当于{{ printf "%s" "Hello World!" }}

See an example in the Go Playground here

基本上,

{{ "Hello World!" | printf "%s"           }}
    ^^^^^^^^^^^^               ^^^^^^^^^^
         |__________________________|

这在函数式语言中非常普遍(从我所见过的......我知道它在F#中的一个东西。)

点。

点是“上下文意识”。这意味着,它取决于你把它放在哪里改变意义。当您在模板的正常区域中使用它时,它就是您的模型。在range循环中使用它时,它将成为迭代的当前值。

See an example in the Go Playground here

在链接示例中,仅在范围循环中,$x.相同。循环结束后,点返回传递给模板的模型。

检查“struct”

您的结构是键值对... map。为此,您需要确保在范围循环中提取两个部分:

{{ range $key, $value = . }}

这将为您提供每次迭代时的键和值。之后,您只需要检查相等性:

{{ if eq $key "struct" }}
    {{ /* $value.ID is the ID you want */ }}

See an example on the Go Playground here

希望这有帮助。