问题描述

我有一个 Golang 模板,定义如下

I have a Golang template, defined like this

{{- define "test" -}}
{{- printf "%s" .Name | trunc 24 -}}
{{- end -}}

然后我在我的一个文件中使用它:

Then I use it in one of my files:

{{ template "test" . }}

测试”后的点是什么意思?Golang 模板文档说:

What does the dot mean after “test”? Golang template docs say:

{{template "name" pipeline}}
The template with the specified name is executed with dot set
to the value of the pipeline.

但我不确定管道是什么.看文档没有结果,谁能再解释一下?

But I am not sure what pipeline is. Reading documentation gave no results, could anyone explain once again?

{{ - printf "%s" .Name |截断 24 -}}
{{ - printf "%s" .Name | trunc 24 -}}

先谢谢你!

推荐答案

templatetext/templatehtml/模板
templatetext/templatehtml/template
html/templatetext/template
html/templatetext/template
html/templatetext/htmlhtml/template
html/templatetext/htmlhtml/template
text/template
text/template

管道是可能链接的命令”序列.命令是一个简单的值(参数)或函数或方法调用,可能带有多个参数:

Pipelines

A pipeline is a possibly chained sequence of “commands”. A command is a simple value (argument) or a function or method call, possibly with multiple arguments:

Argument
    The result is the value of evaluating the argument.
.Method [Argument...]
    The method can be alone or the last element of a chain but,
    unlike methods in the middle of a chain, it can take arguments.
    The result is the value of calling the method with the
    arguments:
        dot.Method(Argument1, etc.)
functionName [Argument...]
    The result is the value of calling the function associated
    with the name:
        function(Argument1, etc.)
    Functions and function names are described below.

可以通过使用管道字符|”分隔命令序列来链接”管道.在链式管道中,每个命令的结果作为以下命令的最后一个参数传递.管道中最后一个命令的输出就是管道的值.

A pipeline may be “chained” by separating a sequence of commands with pipeline characters ‘|’. In a chained pipeline, the result of each command is passed as the last argument of the following command. The output of the final command in the pipeline is the value of the pipeline.

参数”和管道”是对数据的评估.

“Arguments” and “pipelines” are evaluations of data.

.{{range}}{{with}}
.{{range}}{{with}}

模板的执行会遍历结构并设置光标,用句点.”表示.并称为点”,随着执行的进行到结构中当前位置的值.

Execution of the template walks the structure and sets the cursor, represented by a period ‘.’ and called “dot”, to the value at the current location in the structure as execution proceeds.

.NameNamestruct.NameNameName()
.NameNamestruct.NameNameName()
{{template "something" .}}Name{{template "something" .Name}}
{{template "something" .}}Name{{template "something" .Name}}
{{template}}
{{template}}
$
$

执行开始时,$设置为传递给Execute的数据参数,即dot的起始值.

When execution begins, $ is set to the data argument passed to Execute, that is, to the starting value of dot.

{{range}}
{{range}}
{{range .Books}}Name{{range}}
{{range .Books}}Name{{range}}
{{range .Books}}
    Title: {{.Title}}
    Original name: {{$.Name}}
{{end}}

这篇关于Golang 模板引擎管道的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,WP2