【问题标题】:Render a partial template with passed parameters使用传递的参数渲染部分模板
【发布时间】:2016-03-28 09:35:14
【问题描述】:

我知道在 Ruby 中可以渲染带有附加参数的部分模板,我该如何在 Go 中做到这一点?

我有一个部分模板_partial1.tmpl:

<div>
text1
{{if foo}}
   text2
{{end}}
</div>

从父模板parent.tmpl使用它:

<div>
  {{ template "partial1",  }} // how do I pass foo param here?? 
</div>  

如何将参数foo 传递给部分?

【问题讨论】:

    标签: go go-templates


    【解决方案1】:

    documentation 声明 template 指令有两种形式:

    {{template "name"}}
    执行指定名称的模板 零数据。

    {{template "name" pipeline}}
    具有指定名称的模板是 执行时将点设置为管道的值。

    后者接受一个管道语句,然后在执行的模板中将其值设置为dot 值。所以调用

    {{template "partial1" "string1"}}
    

    将在partial1 模板中将{{.}} 设置为"string1"。因此,虽然无法在部分中设置名称foo,但您可以传递参数,它们将出现在. 中。示例:

    模板.html

    <div>
      {{ template "partial1.html" "muh"}} // how do I pass foo param here??
    </div>
    

    partial1.html

    {{if eq . "muh"}}
    blep
    {{else}}
    moep
    {{end}}
    

    main.go

    import (
        "html/template"
        "fmt"
        "os"
    )
    
    func main() {
        t,err := template.ParseFiles("template.html", "partial1.html")
    
        if err != nil { panic(err) }
    
        fmt.Println(t.Execute(os.Stdout, nil))
    }
    

    运行此程序将打印模板的内容,其中包含来自部分的blep。更改传递的值将更改此行为。

    您还可以分配变量,因此可以在部分中将. 分配给foo:

    {{ $foo := . }}
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-05-23
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2011-02-25
      相关资源
      最近更新 更多