ForeverConfused
ForeverConfused

Reputation: 1777

How do I include something only if it hasn't already been included in FreeMarker?

PHP has a function include_once('target') such that it will include target but only if it hasn't been included before. Does freemarker have something like this?

Include Once prevents errors by not having to handle the dependencies with code. I have a bunch of shell scripts that install applications I'm templating. When I use the scala import, and want to be able to state in the template it has a dependency on java, but if the hadoop template was already included then it already included java. No need to include the java installation script twice. Can freemarker do this?

Upvotes: 0

Views: 176

Answers (1)

ddekany
ddekany

Reputation: 31162

There's no such directive built in, but it can be emulated with a macro, as far as you don't use relative paths at least:

<#global incuded = {}>

<#macro includeOnce path>
  <#if !path?startsWith('/')>
    <#stop "The path must start with /">
  </#if>
  <#if incuded[path]??><#return></#if>
  <#include path>
  <#global incuded += {path: true}>
</#macro>

And then:

<@includeOnce '/something.foo' />

Upvotes: 2

Related Questions