在Revel中从ViewArg选择模板

时间:2018-08-31 22:46:54

标签: go revel

使用Revel框架,是否可以根据ViewArg的值选择模板?

我定义了一个基本控制器,该控制器提供了一种在 views / Layout.html

中呈现内容的方法
type Controller struct {
    *revel.Controller
}

func(c *Controller) RenderView(view string, extraViewArgs ...interface{}) revel.Result {
    // ... omitted source
    c.ViewArgs["ContentTemplateName"] = view

    return c.RenderTemplate("layout.html")
}

实现此目的的示例控制器如下

type MyController struct {
    Controller
}

func (c MyController) Index() revel.Result {
    bananas := "This is bananas"
    return c.RenderView("App/Bananas.html", bananas)
}

然后我尝试在layout.html中渲染“ App / Bananas.html”

{{set . "title" "Home"}}
{{template "header.html" .}}

<div class="container">
  <div class="row">
    {{template "flash.html" .}}
  </div>
  <!-- Left column of Content -->
  <div class="col-md-9 col-sm-8 col-xs-12">
    {{template .ContentTemplateName .}}
  </div>
  <!-- //Left Column of Content -->

  <!-- Right column of summary -->
  <div class="col-md-3 col-sm-4 hidden-xs">
    <div class="container">
      {{template "sidebar.html" .}}
    </div>
  </div>
  <!-- //Right column of summary -->
</div>

{{template "footer.html" .}}

这将输出以下结果

ERROR 2018/08/31 17:46:10 template.go:338: Template compilation error (In layout.html around line 10):
unexpected ".ContentTe"... in template clause
ERROR 2018/08/31 17:46:10 server.go:99: Template Compilation Error (in layout.html:10): unexpected ".ContentTe"... in template clause

1 个答案:

答案 0 :(得分:0)

根据@ mh-cbon的评论,发现不可能使用变量作为template函数的输入

为解决该问题以使其更接近所需功能,我实施了以下(不太理想的)解决方案:

base_content_view.html

{{template "begin_content.html" . }}
  <!-- content here -->
{{template "end_content.html" . }}

begin_content.html

{{template "header.html" . }}

<div class="container">
  <div class="row">
    {{template "flash.html" .}}
  </div>
    <!-- Left column of Content -->
  <div class="col-md-9 col-sm-8 col-xs-12">    

end_content.html

  </div>
  <!-- //Left Column of Content -->

  <!-- Right column of summary -->
  <div class="col-md-3 col-sm-4 hidden-xs">
    <div class="container">
      {{template "sidebar.html" .}}
    </div>
  </div>
  <!-- //Right column of summary -->

{{template "footer.html" .}}

base_content_view.html是一个静态文件,在制作新视图时会复制粘贴为模板。此设计确实存在其他问题,但是它是限制template函数的示例变通方法。