How can I pass data as arguments to an included template in Go\'s templating system?

DDD
Release: 2024-10-28 04:29:30
Original
617 people have browsed it

How can I pass data as arguments to an included template in Go's templating system?

Passing Data Between Templates

In Go's templating system, it can be necessary to pass data between multiple templates, particularly when including one template within another. The question arises, "How can I pass data as arguments to an included template and access it within that template?"

To achieve this, you can utilize a custom function that merges the arguments into a single slice value. By registering this function, it can be used within the template invocation. The following code demonstrates how this is done:

<code class="go">package main

import (
    "fmt"
    "html/template"
)

func main() {
    t, err := template.New("t").Funcs(template.FuncMap{
        "args": func(vs ...interface{}) []interface{} { return vs },
    }).Parse("{{ template \"image_row\" args . 5 }}")
    if err != nil {
        fmt.Println(err)
        return
    }

    err = t.Execute(template.Must(template.ParseFiles("index.html", "image_row.html")), nil)
    if err != nil {
        fmt.Println(err)
        return
    }
}

// index.html
{{ template "image_row" . | 5 }}

// image_row.html
{{ define "image_row" }}
   To stuff here {{index . 0}} {{index . 1}}
{{ end }}</code>
Copy after login

Within the image_row template, the arguments can be accessed using the built-in index function. For example, {{index . 0}} would access the first argument (index 0) passed from the index.html template, in this case the number 5.

This solution provides a versatile way to pass and access data between multiple templates, enabling custom functionality and efficient code reuse.

The above is the detailed content of How can I pass data as arguments to an included template in Go\'s templating system?. 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!