gpt4 book ai didi

Go blue-jay/blueprint,如何在 Controller 中分配变量并在 html/模板 View 中使用它?

转载 作者:IT王子 更新时间:2023-10-29 02:09:55 26 4
gpt4 key购买 nike

blue-jay/blueprint 是一个 MVC ( https://blue-jay.github.io/views/ ) 快速启动 golang webapp,具有针对 mysql 的 CRUD 和其他开箱即用的功能。

“结构”中的数据库字段没有问题,它们加载和呈现都很好。如何声明与数据库字段或“结构”无关的变量。

controller/categories/category.go:

// Package category provides a simple CRUD in a web page.
package category

import (
"net/http"

"github.com/blue-jay/blueprint/lib/flight"
"github.com/blue-jay/blueprint/middleware/acl"
"github.com/blue-jay/blueprint/model/category"
"github.com/blue-jay/core/form"
"github.com/blue-jay/core/pagination"
"github.com/blue-jay/core/router"
)

var (
uri = "/categories"
)

// Load routes.
func Load() {
c := router.Chain(acl.DisallowAnon)
router.Get(uri, Index, c...)
router.Get(uri+"/create", Create, c...)
router.Post(uri+"/create", Store, c...)
}

// Create displays html page.
func Create(w http.ResponseWriter, r *http.Request) {
c := flight.Context(w, r)
v := c.View.New("categories/create")
v.Vars["test"] = "Testing" <--- VARIABLE IN QUESTION

form.Repopulate(
r.Form,
v.Vars,
"parent_id",
"title",
"icon",
"description",
"url",
"sort",
"status_id",
"guid_id",
"role_id",
"user_id")
v.Render(w, r)
}

查看/类别/create.tmpl

{{define "title"}}New Category{{end}}
{{define "head"}}{{end}}
{{define "content"}}
<div class="page-header"><h1>{{template "title" .}}</h1></div>
{{ .test }} <--- VARIABLE IN QUESTION
{{template "footer" .}}
{{end}}
{{define "foot"}}{{end}}

为了简洁起见,我删除了大部分表格和模型 (model/category/category.go)。

我们在这里寻找的是如何从 Controller 中创建和填充变量“test”,并让它在模板中显示其值“Testing”。目前,它输出什么都没有。

让我感到困惑的是,我已经声明了一个变量“guid”,并在另一个 Controller 中以这种方式(貌似)调用它(“controller/register/register.go”在 func Index 中,输出在/view/register 中/index.tmpl 在下面的 github 链接中找到。)这似乎工作正常。我在这里找不到我在做什么。我显然不明白的东西。

其余代码:https://github.com/iamtoc/blueprint-ledger

进入 golang 才几天,所以还是很新。关于这怎么可能的任何想法?谢谢!

最佳答案

我检查了你的 github 存储库,发现了很多损坏的导入,比如

"github.com/blue-jay/blueprint/model/category"

blue-jay/blueprint 替换为您的 repo 路径 iamtoc/blueprint-ledger 后,我能够运行您的原始代码

v.Vars["test"] = "Testing"  <--- VARIABLE IN QUESTION

form.Repopulate(
r.Form,
v.Vars,
"parent_id",
...

没有任何问题,可以看到打印出的测试模板变量。我怀疑,您只是错误地复制了原始的 blue-jay/blueprint 项目,因为我还使用原始 repo 测试了这个案例,它再次按预期工作。

关于Go blue-jay/blueprint,如何在 Controller 中分配变量并在 html/模板 View 中使用它?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49890201/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com