How to Pass Data to Included Templates in Go?

Mary-Kate Olsen
Release: 2024-10-26 13:27:03
Original
215 people have browsed it

How to Pass Data to Included Templates in Go?

Passing Data to Rendered Templates in Go

In Go templates, including another template is a straightforward process using the {{ template "include-template-name" }} syntax. However, sometimes it becomes necessary to pass additional data to the included template.

Introducing Dynamic Parameter Passing

Consider a scenario where you want to pass a number to a template, "image_row.html", that uses this number to construct rows dynamically. This requires passing the number as an additional argument to the template invocation.

Custom Function for Passing Multiple Arguments

Since there's no built-in support for passing multiple arguments to a template, you can create a custom function to merge the arguments into a single slice. Register this function with Funcs and use it in the template invocation:

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

Usage in Template Invocation

Inside the main template, you can pass the arguments using the args function:

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

Accessing Arguments in Included Template

Within "image_row.html", you can access the arguments using the built-in index function:

{{ define "image_row" }}
   To stuff here {{index . 0}} {{index . 1}}
{{ end }}
Copy after login

This approach allows you to pass dynamic data to rendered templates, enabling greater flexibility in template design and data handling.

The above is the detailed content of How to Pass Data to Included Templates in Go?. 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
Latest Articles by Author
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!