templates - 如何将变量传递给模板并在 beego 中接收变量

标签 templates go beego go-templates

我的模板文件:

{{range $index, $option := .alternatives}}
<div id="splashAlternative{{$index}}" class="col-sm-2">
    <select id="flashSrc_{{$index}}">
    {{template "alternative_src.html" $option}}
    </select>
</div>
{{end}}

我想将 $option 传递给模板,以及 alternative_src.html 代码:

{{if compare .option ""}}
  <option value="" selected="selected">
  </option>
{{else}}
  <option value=""></option>
{{end}}
{{if compare .option "xxx"}}
  <option value="xxx" selected="selected">xxx</option>
{{else}}
  <option value="xxx">xxx</option>
{{end}}

但我遇到以下问题:

executing "alternative_src.html" at <.option>: can't evaluate field option in type string

最佳答案

当您使用 {{template}} 操作并传递一些内容时,它会成为被调用模板中的点 .。引用自 text/template 的包文档:

{{template "name" pipeline}}
    The template with the specified name is executed with dot set
    to the value of the pipeline.

因此在 alternative_src.html 中仅将选项称为点 .(点 . 表示管道的值传递给模板,即调用者模板中的$option):

{{if compare . ""}}
  <option value="" selected="selected">
  </option>
{{else}}
  <option value=""></option>
{{end}}
{{if compare . "xxx"}}
  <option value="xxx" selected="selected">xxx</option>
{{else}}
  <option value="xxx">xxx</option>
{{end}}

关于templates - 如何将变量传递给模板并在 beego 中接收变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38869860/

相关文章:

c++ - 使用仿函数模板或继承库

wpf - 项目更改时如何触发 cellTemplateSelector

python - 如何修复 CSRF 验证错误?

go - 复制有条件的目录

go - 如何正确使用beego框架的RelatedSel()方法

c++ - 删除 decltype 中的引用(返回 T 而不是 T&,其中 T& 是 decltype)

go - 如何在函数中传递指向结构的指针?

google-app-engine - 在 beegae 中使用 CSS

javascript - 将 javascript 与 beego 结合使用

sql-server - 带有 Golang SQL 驱动程序和 UUID 的 MS SQL 唯一标识符