消息关闭
    暂无新消息!

go template中{{ $mac }} 和 {{ .mac }} 有什么区别吗?
看到两种写法都有


2个回答

︿ 3
  1. 点号用于输出当前对象的值

  2. 美元符号用于输出模板中定义变量的值

    m := map[string]string{
        "who": "map",
    }
    t, err := template.New("test").Parse(`{{.who}}{{$who := "template"}}{{$who}}`)
    if err != nil {
        log.Fatalln(err)
    }
    //输出"maptemplate",
    if err := t.Execute(os.Stdout, m); err != nil {
        log.Fatalln(err)
    }
︿ 2

看官方文档……

dollar表示变量,即{{ $a }}

点表示结构体(变量)的一个成员,只传入一个结构体的话,可以省略结构体变量的名,{{ $a.a }}可以省略为{{ .a }}

- A boolean, string, character, integer, floating-point, imaginary
  or complex constant in Go syntax. These behave like Go's untyped
  constants.
- The keyword nil, representing an untyped Go nil.
- The character '.' (period):
    .
  The result is the value of dot.
- A variable name, which is a (possibly empty) alphanumeric string
  preceded by a dollar sign, such as
    $piOver2
  or
    $
  The result is the value of the variable.
  Variables are described below.
- The name of a field of the data, which must be a struct, preceded
  by a period, such as
    .Field
  The result is the value of the field. Field invocations may be
  chained:
    .Field1.Field2
  Fields can also be evaluated on variables, including chaining:
    $x.Field1.Field2
- The name of a key of the data, which must be a map, preceded
  by a period, such as
    .Key
  The result is the map element value indexed by the key.
  Key invocations may be chained and combined with fields to any
  depth:
    .Field1.Key1.Field2.Key2
  Although the key must be an alphanumeric identifier, unlike with
  field names they do not need to start with an upper case letter.
  Keys can also be evaluated on variables, including chaining:
    $x.key1.key2
- The name of a niladic method of the data, preceded by a period,
  such as
    .Method
  The result is the value of invoking the method with dot as the
  receiver, dot.Method(). Such a method must have one return value (of
  any type) or two return values, the second of which is an error.
  If it has two and the returned error is non-nil, execution terminates
  and an error is returned to the caller as the value of Execute.
  Method invocations may be chained and combined with fields and keys
  to any depth:
    .Field1.Key1.Method1.Field2.Key2.Method2
  Methods can also be evaluated on variables, including chaining:
    $x.Method1.Field
- The name of a niladic function, such as
    fun
  The result is the value of invoking the function, fun(). The return
  types and values behave as in methods. Functions and function
  names are described below.
- A parenthesized instance of one the above, for grouping. The result
  may be accessed by a field or map key invocation.
    print (.F1 arg1) (.F2 arg2)
    (.StructValuedMethod "arg").Field

这种东西中文资料都一搜一大把……

http://www.cnblogs.com/Pynix/...