Home >Backend Development >Golang >How to parse an embed.FS template using the template.ParseFS function

How to parse an embed.FS template using the template.ParseFS function

WBOY
WBOYforward
2024-02-13 08:57:08666browse

如何使用 template.ParseFS 函数解析 embed.FS 模板

php editor Xiaoxin brings you a guide on how to use the template.ParseFS function to parse the embed.FS template. When developing projects using the Go language, we often use the embed package to embed static files, and the template.ParseFS function can help us parse these embedded template files. This article will introduce in detail how to use the template.ParseFS function to help you process template files more flexibly during the development process and improve the development efficiency of the project. Let’s take a look!

Question content

I want to parse all templates in the same template.Template structure but I don't know how to parse and it also gives me an error. I have next code:

package main

import (
    "embed"
    "html/template"
    "log"
    "os"
)

//go:embed internal/web/views/*
var viewsFS embed.FS

func main() {
    tmpls, err := template.New("").ParseFS(viewsFS, "**/*.html")
    if err != nil {
        log.Fatal(err) // Debugging I finded out that the error is here so the code below is irrelevant
    }
    tmpls.ExecuteTemplate(os.Stdout, "pages/home", nil)
}

Give me ParseFS The error in the method is next:

$ 2023/09/16 23:36:42 template: pattern matches no files: `**/*.html`

I think the error is in the patterns parameter of the ParseFS method, I don't know.

I have many html files in the internal/web/views directory. In fact, all the files in this folder are html files, and each file has one or more { {define}} type template. p>

Any help would be greatly appreciated, thank you

Solution

@Charlie-Tumahai Credits this Documentation (Go Package Official Website) Global patterns in Go

So, in order to parse all templates in the same template.Template structure, I have to do the following:

package main

import (
    "embed"
    "html/template"
    "log"
    "os"
)

//go:embed internal/web/views/*
var viewsFS embed.FS

func main() {
    tmpls, err := template.New("").
        ParseFS(viewsFS,
            "internal/web/views/*/*.html",
            "internal/web/views/*/*/*.html",
            /* Add more `*` if you have templates that are more nested */
        )
    if err != nil {
        log.Fatal(err)
    }
    tmpls.ExecuteTemplate(os.Stdout, "pages/home", nil)
}

What I did was look into the Glob pattern more and learn how to use it in Go, the Glob pattern in Go is made differently than in any other language.

The above is the detailed content of How to parse an embed.FS template using the template.ParseFS function. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:stackoverflow.com. If there is any infringement, please contact admin@php.cn delete