douju8113 2019-01-01 15:22
浏览 190

如何在嵌套golang模板中使用自定义函数?

I have a webpage consisting of one layout.html and one content.html. Both contain calls to a custom function for translating strings.

When I call template.ParseFiles, the content is included into the layout and is served, but only strings in layout.html are translated while the strings from content.html disappear.

This works fine when I use single html files, but I can't get it work with nested files.

main.go

func executeMultiTmpl(w http.ResponseWriter, r *http.Request) {

  funcMap := template.FuncMap{
    "index": lookup,
  }
  tmpl, err := template.New("example.html").Funcs(funcMap).ParseFiles(
    "dev/html/example/layout.html",
    "dev/html/example/content.html",
  )
   var tpl bytes.Buffer
   err = tmpl.Execute(&tpl ,Translation)
   if err != nil {
    panic(err)
   }
}

layout.html

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Example Title - {{index . "About"}}</title>
</head>
<body>

{{ template "content.html" }}

</body>
</html>

content.html

<h2>{{index . "Some headline"}}</h2>

The file content.html is nested inside of layout.html. Afterwards the function lookup receives a map Translation and translates all strings in the layout.html file which are surrounded by {{index . }}. Unfortunately, the strings in the file content.html are not translated.

I know the function lookup is called, but it receives an empty Translation map.

When I remove the custom function and run it with the standard index function, I get a panic: executing "content.html" at : error calling index: index of untyped nil

  • 写回答

0条回答 默认 最新

    报告相同问题?

    悬赏问题

    • ¥15 thinkphp6配合social login单点登录问题
    • ¥15 HFSS 中的 H 场图与 MATLAB 中绘制的 B1 场 部分对应不上
    • ¥15 如何在scanpy上做差异基因和通路富集?
    • ¥20 关于#硬件工程#的问题,请各位专家解答!
    • ¥15 关于#matlab#的问题:期望的系统闭环传递函数为G(s)=wn^2/s^2+2¢wn+wn^2阻尼系数¢=0.707,使系统具有较小的超调量
    • ¥15 FLUENT如何实现在堆积颗粒的上表面加载高斯热源
    • ¥30 截图中的mathematics程序转换成matlab
    • ¥15 动力学代码报错,维度不匹配
    • ¥15 Power query添加列问题
    • ¥50 Kubernetes&Fission&Eleasticsearch