Я только начинаю использовать 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
Как назначить переменную шаблона GO внутри шаблона GO? ⇐ Html
Программисты Html
-
Anonymous
1741678767
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()
}
Подробнее здесь: [url]https://stackoverflow.com/questions/76231211/how-to-assign-a-variable-of-a-go-template-inside-a-go-template[/url]
Ответить
1 сообщение
• Страница 1 из 1
Перейти
- Кемерово-IT
- ↳ Javascript
- ↳ C#
- ↳ JAVA
- ↳ Elasticsearch aggregation
- ↳ Python
- ↳ Php
- ↳ Android
- ↳ Html
- ↳ Jquery
- ↳ C++
- ↳ IOS
- ↳ CSS
- ↳ Excel
- ↳ Linux
- ↳ Apache
- ↳ MySql
- Детский мир
- Для души
- ↳ Музыкальные инструменты даром
- ↳ Печатная продукция даром
- Внешняя красота и здоровье
- ↳ Одежда и обувь для взрослых даром
- ↳ Товары для здоровья
- ↳ Физкультура и спорт
- Техника - даром!
- ↳ Автомобилистам
- ↳ Компьютерная техника
- ↳ Плиты: газовые и электрические
- ↳ Холодильники
- ↳ Стиральные машины
- ↳ Телевизоры
- ↳ Телефоны, смартфоны, плашеты
- ↳ Швейные машинки
- ↳ Прочая электроника и техника
- ↳ Фототехника
- Ремонт и интерьер
- ↳ Стройматериалы, инструмент
- ↳ Мебель и предметы интерьера даром
- ↳ Cантехника
- Другие темы
- ↳ Разное даром
- ↳ Давай меняться!
- ↳ Отдам\возьму за копеечку
- ↳ Работа и подработка в Кемерове
- ↳ Давай с тобой поговорим...
Мобильная версия