外部模板

ent 接受外部 Go 模板 以使用 --template 标志执行。 如果外部模板名在 ent 中已经定义过,它会覆盖已经定义的外部模板。 如果没有定义过,在命令执行完成后,会生成一个与外部模板同名的文件。 例如:

stringer.tmpl - 这个外部模板示例文件会生成一个叫做ent/stringer.go的文件。

  1. {{/* 下一行的作用是,告诉 Intellij/GoLand 等IDE,基于 gen.Graph 类型来启用自动补全功能。 */}}
  2. {{/* gotype: entgo.io/ent/entc/gen.Graph */}}
  3. {{ define "stringer" }}
  4. {{/* Add the base header for the generated file */}}
  5. {{ $pkg := base $.Config.Package }}
  6. {{ template "header" $ }}
  7. {{/* Loop over all nodes and implement the "GoStringer" interface */}}
  8. {{ range $n := $.Nodes }}
  9. {{ $receiver := $n.Receiver }}
  10. func ({{ $receiver }} *{{ $n.Name }}) GoString() string {
  11. if {{ $receiver }} == nil {
  12. return fmt.Sprintf("{{ $n.Name }}(nil)")
  13. }
  14. return {{ $receiver }}.String()
  15. }
  16. {{ end }}
  17. {{ end }}

debug.tmpl - 这个模板文件会生成一个叫做ent/debug.go的文件

  1. {{ define "debug" }}
  2. {{/* 此模板用于给运行在debug模式下的每个 client<T> 添加一些功能。 */}}
  3. {{/* 给生成的文件添加头部信息 */}}
  4. {{ $pkg := base $.Config.Package }}
  5. {{ template "header" $ }}
  6. {{/* 循环遍历所有节点,并且给配置项添加 "Debug" 方法 */}}
  7. {{ range $n := $.Nodes }}
  8. {{ $client := print $n.Name "Client" }}
  9. func (c *{{ $client }}) Debug() *{{ $client }} {
  10. if c.debug {
  11. return c
  12. }
  13. cfg := config{driver: dialect.Debug(c.driver, c.log), log: c.log, debug: true, hooks: c.hooks}
  14. return &{{ $client }}{config: cfg}
  15. }
  16. {{ end }}
  17. {{ end }}

通过模板名对现有模板进行覆盖。 示例如下:

  1. {{/* 此模板用于给实体添加一些字段。 */}}
  2. {{ define "model/fields/additional" }}
  3. {{- /* 给 "Card" 实体添加静态字段。 */}}
  4. {{- if eq $.Name "Card" }}
  5. // 通过模板定义静态字段。
  6. StaticField string `json:"static_field,omitempty"`
  7. {{- end }}
  8. {{ end }}

Helper Templates

As mentioned above, ent writes each template’s execution output to a file named the same as the template. For example, the output from a template defined as {{ define "stringer" }} will be written to a file named ent/stringer.go.

By default, ent writes each template declared with {{ define "<name>" }} to a file. However, it is sometimes desirable to define helper templates - templates that will not be invoked directly but rather be executed by other templates. To facilitate this use case, ent supports two naming formats that designate a template as a helper. The formats are:

1. {{ define "helper/.+" }} for global helper templates. For example:

  1. {{ define "helper/foo" }}
  2. {{/* Logic goes here. */}}
  3. {{ end }}
  4. {{ define "helper/bar/baz" }}
  5. {{/* Logic goes here. */}}
  6. {{ end }}

2. {{ define "<root-template>/helper/.+" }} for local helper templates. A template is considered as “root” if its execution output is written to a file. For example:

  1. {{/* A root template that is executed on the `gen.Graph` and will be written to a file named: `ent/http.go`.*/}}
  2. {{ define "http" }}
  3. {{ range $n := $.Nodes }}
  4. {{ template "http/helper/get" $n }}
  5. {{ template "http/helper/post" $n }}
  6. {{ end }}
  7. {{ end }}
  8. {{/* A helper template that is executed on `gen.Type` */}}
  9. {{ define "http/helper/get" }}
  10. {{/* Logic goes here. */}}
  11. {{ end }}
  12. {{/* A helper template that is executed on `gen.Type` */}}
  13. {{ define "http/helper/post" }}
  14. {{/* Logic goes here. */}}
  15. {{ end }}

Annotations

Schema annotations allow attaching metadata to fields and edges and inject them to external templates.
An annotation must be a Go type that is serializable to JSON raw value (e.g. struct, map or slice) and implement the Annotation interface.

Here’s an example of an annotation and its usage in schema and template:

1. 定义一个注解

  1. package entgql
  2. // Annotation annotates fields with metadata for templates.
  3. type Annotation struct {
  4. // OrderField is the ordering field as defined in graphql schema.
  5. OrderField string
  6. }
  7. // Name implements ent.Annotation interface.
  8. func (Annotation) Name() string {
  9. return "EntGQL"
  10. }

2. Annotation usage in ent/schema:

  1. // User schema.
  2. type User struct {
  3. ent.Schema
  4. }
  5. // Fields of the user.
  6. func (User) Fields() []ent.Field {
  7. return []ent.Field{
  8. field.Time("creation_date").
  9. Annotations(entgql.Annotation{
  10. OrderField: "CREATED_AT",
  11. }),
  12. }
  13. }

3. 注解在外部模板中的用法:

  1. {{ range $node := $.Nodes }}
  2. {{ range $f := $node.Fields }}
  3. {{/* Get the annotation by its name. See: Annotation.Name */}}
  4. {{ if $annotation := $f.Annotations.EntGQL }}
  5. {{/* Get the field from the annotation. */}}
  6. {{ $orderField := $annotation.OrderField }}
  7. {{ end }}
  8. {{ end }}
  9. {{ end }}

Global Annotations

Global annotation is a type of annotation that is injected into the gen.Config object and can be accessed globally in all templates. For example, an annotation that holds a config file information (e.g. gqlgen.yml or swagger.yml) add can accessed in all templates:

1. An annotation definition:

  1. package gqlconfig
  2. import (
  3. "entgo.io/ent/schema"
  4. "github.com/99designs/gqlgen/codegen/config"
  5. )
  6. // Annotation defines a custom annotation
  7. // to be inject globally to all templates.
  8. type Annotation struct {
  9. Config *config.Config
  10. }
  11. func (Annotation) Name() string {
  12. return "GQL"
  13. }
  14. var _ schema.Annotation = (*Annotation)(nil)

2. Annotation usage in ent/entc.go:

  1. func main() {
  2. cfg, err := config.LoadConfig("<path to gqlgen.yml>")
  3. if err != nil {
  4. log.Fatalf("loading gqlgen config: %v", err)
  5. }
  6. opts := []entc.Option{
  7. entc.TemplateDir("./template"),
  8. entc.Annotations(gqlconfig.Annotation{Config: cfg}),
  9. }
  10. err = entc.Generate("./schema", &gen.Config{
  11. Templates: entgql.AllTemplates,
  12. }, opts...)
  13. if err != nil {
  14. log.Fatalf("running ent codegen: %v", err)
  15. }
  16. }

3. Annotation usage in external templates:

  1. {{- with $.Annotations.GQL.Config.StructTag }}
  2. {{/* Access the GQL configuration on *gen.Graph */}}
  3. {{- end }}
  4. {{ range $node := $.Nodes }}
  5. {{- with $node.Config.Annotations.GQL.Config.StructTag }}
  6. {{/* Access the GQL configuration on *gen.Type */}}
  7. {{- end }}
  8. {{ end }}

Examples

  • 一个实现GraphQL Node API的自定义模板 - Github

  • 一个用自定义函数执行外部模板的例子。 参阅配置和它的README文件。

Documentation

Templates are executed on either a specific node type, or the entire schema graph. For API documentation, see the GoDoc.

AutoCompletion

JetBrains users can add the following template annotation to enable the autocompletion in their templates:

  1. {{/* The line below tells Intellij/GoLand to enable the autocompletion based on the *gen.Graph type. */}}
  2. {{/* gotype: entgo.io/ent/entc/gen.Graph */}}
  3. {{ define "template" }}
  4. {{/* ... */}}
  5. {{ end }}

See it in action:

template-autocomplete