casid / jte

Secure and speedy templates for Java and Kotlin.
https://jte.gg
Apache License 2.0
848 stars 63 forks source link

dynamic @template calls #393

Closed meouwu-dev closed 1 month ago

meouwu-dev commented 1 month ago

Hello, thanks for creating this library. Is there a way to dynamically load a template with @template calls?

For example, I have some .jte files located in jte/page/report folder. I would like to dynamically load these templates based on a list of report types (passed from params). The following code does not work, but I would like to know if there is a way to achieve this.

@for (type in reportTypeList)
  @template.page.report.${type}()
@endfor

Thanks for your help.

casid commented 1 month ago

Hi @meouwu-dev!

no, this is not supported through @template calls.

However, you can provide a Kotlin method to do this, if you have TemplateEngine and the current TemplateOutput at hand and call templateEngine.render("page/report/" + type + ".kte")

However, sometimes different Pages might need different parameters. In Java I like to use instanceof pattern matching in if statements for such cases, I think this should work in .kte templates too!

In jte this might look like

@if(type instanceof ReportA reportA)
   @template.page.report.reportA(reportA)
@elseif(type instanceof ReportB reportB)
   ...
@endif

Which fits nicely with the type safety benefits. Hope this helps!

meouwu-dev commented 1 month ago

Hi @casid , thank you for your quick response. I will try templateEngine.render().