Home  >  Article  >  Backend Development  >  How to Pass Data Between Templates in Go\'s text/template Package?

How to Pass Data Between Templates in Go\'s text/template Package?

DDD
DDDOriginal
2024-10-27 02:59:03619browse

How to Pass Data Between Templates in Go's text/template Package?

Passing Data Between Templates

A common requirement in template rendering is the ability to pass data between templates. In Go's text/template package, this can be achieved using a combination of functions and template invocation techniques.

To pass a simple number as an additional argument to a nested template, you can define a function that merges its arguments into a single slice value. This function can then be registered and used in the template invocation.

Here's an example:

<code class="go">func args(vs ...interface{}) []interface{} {
    return vs
}</code>
<code class="go">t, err := template.New("t").Funcs(template.FuncMap{"args": args}).Parse(...)</code>

In the index.html template, use the args function to merge the current data with the additional argument:

<code class="html">{{ template "image_row" args . 5 }}</code>

Within the image_row.html template, access the arguments using the index built-in function:

<code class="html">{{ define "image_row" }}
   To stuff here {{ index . 0 }} {{ index . 1 }}
{{ end }}</code>

This approach allows you to pass arbitrary data between templates and build more complex and reusable template components.

The above is the detailed content of How to Pass Data Between Templates in Go\'s text/template Package?. 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