从Golang模板循环获取点击的Vendor Code以在Bootstrap模态框展示对应信息
解决Bootstrap模态框始终显示最后一个供应商数据的问题
问题根源
模板循环渲染时,全局变量$VC在循环结束后会保留最后一个供应商的编码,导致所有模态框绑定的都是同一数据。下面提供两种可行的解决方案:
方案1:前端JS动态获取渲染(推荐,适合大数据量场景)
1. 修改HTML模板,给链接添加供应商编码标识
在index.html的供应商列表循环中,给每个Vendor Code链接加上data-vendcode属性,同时只保留一个空的模态框模板:
{{range .Vendors}} <a href="#" class="vendor-link" data-vendcode="{{.VC}}" data-bs-toggle="modal" data-bs-target="#vendorModal"> {{.VC}} </a> {{end}} <!-- 通用模态框模板,内容留空由JS填充 --> <div class="modal fade" id="vendorModal" tabindex="-1" aria-labelledby="vendorModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="vendorModalLabel">供应商信息</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body" id="vendorModalBody"> <!-- JS动态填充内容 --> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> </div>
2. 后端新增API接口返回供应商数据
在main.go中添加一个接口,根据供应商编码返回对应信息:
package main import ( "encoding/json" "net/http" "text/template" ) type Vendor struct { VC string Name string Address string // 其他自定义字段 } func main() { http.HandleFunc("/", vendAcctPage) http.HandleFunc("/api/vendor/", getVendorByCode) // 新增API路由 http.ListenAndServe(":8001", nil) } // 渲染vendacct页面 func vendAcctPage(w http.ResponseWriter, r *http.Request) { // 模拟供应商数据,实际可从数据库读取 vendors := []Vendor{ {VC: "V001", Name: "供应商A", Address: "XX市XX路1号"}, {VC: "V002", Name: "供应商B", Address: "XX市XX路2号"}, } tmpl, err := template.ParseFiles("test/index.html") if err != nil { http.Error(w, err.Error(), http.StatusInternalServerError) return } tmpl.Execute(w, vendors) } // 根据编码获取供应商数据的API func getVendorByCode(w http.ResponseWriter, r *http.Request) { // 从URL路径中提取供应商编码 vendCode := r.URL.Path[len("/api/vendor/"):] // 调用你的VendorByVendCode()函数获取数据 vend := VendorByVendCode(vendCode) if vend.VC == "" { http.Error(w, "供应商不存在", http.StatusNotFound) return } w.Header().Set("Content-Type", "application/json") json.NewEncoder(w).Encode(vend) } // 你的原有VendorByVendCode函数,这里模拟实现 func VendorByVendCode(code string) Vendor { switch code { case "V001": return Vendor{VC: "V001", Name: "供应商A", Address: "XX市XX路1号"} case "V002": return Vendor{VC: "V002", Name: "供应商B", Address: "XX市XX路2号"} default: return Vendor{} } }
3. 添加JS逻辑获取并填充模态框
在index.html末尾添加JavaScript,监听模态框显示事件,调用API填充对应数据:
<script> const vendorModal = document.getElementById('vendorModal'); // 监听模态框即将显示的事件 vendorModal.addEventListener('show.bs.modal', function (event) { // 获取触发模态框的链接元素 const triggerBtn = event.relatedTarget; // 提取供应商编码 const vendCode = triggerBtn.getAttribute('data-vendcode'); const modalBody = document.getElementById('vendorModalBody'); // 调用后端API获取数据 fetch(`/api/vendor/${vendCode}`) .then(res => { if (!res.ok) throw new Error('未找到该供应商'); return res.json(); }) .then(vendor => { // 填充模态框内容,根据实际字段调整 modalBody.innerHTML = ` <p><strong>供应商编码:</strong> ${vendor.VC}</p> <p><strong>供应商名称:</strong> ${vendor.Name}</p> <p><strong>地址:</strong> ${vendor.Address}</p> `; }) .catch(err => { modalBody.innerHTML = `<p class="text-danger">${err.message}</p>`; }); }); </script>
方案2:后端预渲染每个供应商的模态框(适合小数据量场景)
如果供应商数量不多,可以在模板循环中为每个供应商生成独立的模态框,避免全局变量覆盖问题:
{{range .Vendors}} <a href="#" data-bs-toggle="modal" data-bs-target="#vendorModal-{{.VC}}"> {{.VC}} </a> <!-- 每个供应商对应唯一ID的模态框 --> <div class="modal fade" id="vendorModal-{{.VC}}" tabindex="-1" aria-labelledby="vendorModalLabel-{{.VC}}" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="vendorModalLabel-{{.VC}}">供应商信息: {{.VC}}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <p><strong>供应商编码:</strong> {{.VC}}</p> <p><strong>供应商名称:</strong> {{.Name}}</p> <p><strong>地址:</strong> {{.Address}}</p> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">关闭</button> </div> </div> </div> </div> {{end}}
这种方式无需额外API和JS逻辑,但供应商数量过多会导致HTML体积过大,影响页面加载速度。
内容的提问来源于stack exchange,提问作者JNN
相关产品推荐
相关产品推荐

