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

DDD
Release: 2024-10-27 02:59:03
Original
627 people have browsed it

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>
Copy after login
<code class="go">t, err := template.New("t").Funcs(template.FuncMap{"args": args}).Parse(...)</code>
Copy after login

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>
Copy after login

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>
Copy after login

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!

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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!