Как назначить переменную шаблона GO внутри шаблона GO?Html

Программисты Html
Ответить
Anonymous
 Как назначить переменную шаблона GO внутри шаблона GO?

Сообщение Anonymous »

Я только начинаю использовать Golang и систему шаблонов, чтобы перестроить свой веб -сервер. Теперь я просто хочу написать постоянные переменные для каждого веб -сайта, но я даже не знаю, что я ищу. Я надеюсь, что кто-то может помочь. < /P>
У меня есть этот файл gohtml для «базы» каждого файла html < /p>
{{define "topdoc"}}






{{.title}}




{{end}}

{{define "botdoc"}}



{{end}}
< /code>
, чем я хочу изменить заголовок, а затем, например, описание метадан и подобное так же. < /p>
{{template "topdoc" .}}
{{template "navbar"}}
HOME

{{template "botdoc"}}
< /code>
Navbar определяется в другом файле.{{template "topdoc" .title="Home" .otherParam="Checking..."}}
{{template "navbar"}}
HOME

{{template "botdoc"}}
< /code>
Может быть, кто -то может помочь мне с этой очень тривиальной проблемой. < /p>
Когда я использую этот метод < /p>
{{define "title"}}Home{{end}}
{{template "topdoc"}}
{{template "navbar"}}
HOME

{{template "botdoc"}}
< /code>
и сначала загрузите базовый файл, он показывает пустой веб-сайт.func main() {
r := gin.Default()

tmpl = make(map[string]*template.Template)

// Load templates files
templateFiles := []string{}

fmt.Println("Loading templates...")
// Walk through the "templates" folder and all its subdirectories
nerr := filepath.Walk("main/web/assets/templates", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// Check if the file is an HTML templates
if !info.IsDir() && strings.HasSuffix(info.Name(), ".gohtml") {
// Replace backslashes with forward slashes (for Windows compatibility)
templateName := strings.Replace(path, "\\", "/", -1)

// Parse the file and add it to the "tmpl" map
templateFiles = append(templateFiles, path)

//console log
fmt.Print(templateName + " ")
}
return nil
})

if nerr != nil {
panic(nerr)
}

fmt.Println("\n\nLoading sites...")

// Walk through the "public" folder and all its subdirectories
err := filepath.Walk("main/web/public", func(path string, info os.FileInfo, err error) error {
if err != nil {
return err
}

// Check if the file is an HTML templates
if !info.IsDir() && strings.HasSuffix(info.Name(), ".gohtml") {
// Get the directory path (relative to the "public" folder)
relPath, err := filepath.Rel("main/web/public", filepath.Dir(path))
if err != nil {
return err
}
// Replace backslashes with forward slashes (for Windows compatibility)
templateName := strings.Replace(relPath, "\\", "/", -1)

// Parse the file and add it to the "tmpl" map
parsing := []string{}
parsing = append(parsing, templateFiles...)
parsing = append(parsing, path)

fmt.Println(parsing)

tmpl[templateName] = template.Must(template.ParseFiles(parsing...))

// If the path is empty, default to "index"
if templateName == "." {
templateName = ""
}

// Register the templates with the appropriate route
r.GET("/"+templateName, handler)
}

return nil
})
if err != nil {
panic(err)
}

r.Run()
}


Подробнее здесь: https://stackoverflow.com/questions/762 ... o-template
Ответить

Быстрый ответ

Изменение регистра текста: 
Смайлики
:) :( :oops: :roll: :wink: :muza: :clever: :sorry: :angel: :read: *x)
Ещё смайлики…
   
К этому ответу прикреплено по крайней мере одно вложение.

Если вы не хотите добавлять вложения, оставьте поля пустыми.

Максимально разрешённый размер вложения: 15 МБ.

Вернуться в «Html»