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

DDD
Release: 2024-10-26 03:08:27
Original
195 people have browsed it

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(...)
Copy after login

In index.html:

{{ template "image_row" args . 5 }}
Copy after login

In image_row.html:

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

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

{{ index . 0 }} -> .
{{ index . 1 }} -> 5
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template