Home  >  Article  >  Backend Development  >  How can you pass data from a parent template to a child template in Go templates?

How can you pass data from a parent template to a child template in Go templates?

DDD
DDDOriginal
2024-10-26 03:08:27119browse

How can you pass data from a parent template to a child template in Go templates?

Passing Data Between Templates

Your query concerns passing data from one template to another. You have a parent template (index.html) including a child template (image_row.html) but wish to pass additional data to the child.

The default behavior of templates allows for only the data defined within the parent template to be passed to the child. However, you can achieve your goal by employing some techniques:

Using a Function for Multiple Arguments

One approach is to define a function that aggregates your arguments into a single slice value. You can then register this function and invoke it in the template.

For instance:

import "text/template"

func args(vs ...interface{}) []interface{} { return vs }

t, err := template.New("t").Funcs(template.FuncMap{"args": args}).Parse(...)

In index.html:

{{ template "image_row" args . 5 }}

In image_row.html:

{{ define "image_row" }}
   Data: {{ index . 0 }} {{ index . 1 }}
{{ end }}

This allows you to access your arguments in the child template using the index function:

{{ index . 0 }} -> .
{{ index . 1 }} -> 5

Other Approaches

Alternatively, you could consider:

  • Using a custom template function: Define a custom function within the parent template that generates the necessary data for the child.
  • Passing a struct or map: Construct a struct or map to aggregate the data and pass it to the child template.

Customizing the data passing mechanism in this manner gives you flexibility and control over how data is shared between templates.

The above is the detailed content of How can you pass data from a parent template to a child template in Go templates?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn