Search code examples
template-enginestringtemplate

Nesting one template inside another with StringTemplate 4


I am having problem understanding how to nest another template inside another. For example, I have 3 templates: application.stg, wrapper.stg and core.stg.

core.stg:

page(data1, data2) ::= <<
  <h1>$data1$</h1>
  <h1>$data2$</h1>
>>

wrapper.stg:

page(data3, data4) ::= <<
  <h1>$data3$</h1>

  <!----- CORE.STG GOES HERE ------->

  <h1>$data4$</h1>
>>

application.stg:

   page(data7, data8) ::= <<
      <h1>$data7$</h1>

      <!----- WRAPPER.STG GOES HERE ------->

      <h1>$data8$</h1>
    >>

The documentation seems to hint that this is possible (Conditional Subtemplate section), but sorry, I could not figure out the syntax at all. Please help me out.


Solution

  • You can create a whole file with every template and make sure you set the .stg extension to it. Then create a TemplateGroupFile object and set the properties data7 and data8 and tell it to start in the application template.

    core(data1, data2) ::= <<
      <h1>$data1$</h1>
      <h1>$data2$</h1>
    >>
    
    wrapper(data3, data4) ::= <<
      <h1>$data3$</h1>
      core(data3,data4)
      <h1>$data4$</h1>
    >>
    
    application(data7, data8) ::= <<
      <h1>$data7$</h1>
      wrapper(data7,data8)
      <h1>$data8$</h1>
    >>
    

    This is the C# code

    TemplateGroupFile grp = new TemplateGroupFile(Template);
    Template page_tpl = grp.GetInstanceOf(GroupName);
    GroupName = "application";
    page_tpl.Add("data7", yourData);
    page_tpl.Add("data8", moreOfYourData);
    File.WriteAllText(Path.Combine(dir, Path.GetFileName(outputFile)), page_tpl.Render());