svenkubiak
svenkubiak

Reputation: 672

Freemarker directive or method with boolean return

I am trying to create a custom directive or method in Freemarker that performs a boolean check, e.g.

<#if foo = 'bar'>
do something
</#if>

should be equaivilant to

<@mycheck 'bar'>
do somethng
</@mycheck>

I already worked with custom directives and methods in Freemarker but I didn't find any way to create this with a boolean return.

UPDATE

To make it more clear what I want to do, consider the following: I want to check in a template if it is displayed at a certain URL.

So instead of passing a variable into the template and check via if, like

<#if location = '/home/bar'>
do something
</#if>

I want to do this a little more fluent like this

<@location is='/home/bar'>
do somethng
</@location>

Upvotes: 0

Views: 992

Answers (1)

ddekany
ddekany

Reputation: 31122

You do not have any return value there (unless we consider the output itself as that). You can write a macro like this:

<#macro mycheck value>
  <#if foo == value>
    <#nested>
  </#if>
</#macro>

and then this should work (assuming you have a foo in the data-model or elsewhere where the macro can see it):

<@mycheck 'bar'>
do somethng
</@mycheck>

The solution with TemplateDirectiveModel is very similar, except that unfortunately the argument must be passed by name (<@mycheck expected='bar'>... or something similar), as of 2.3.25 at least. Instead of <#nested> you simply call TemplateDirectiveBody.render(...) in Java, and #if is just a Java if of course.

TemplateMethodModel can't be used for such purpose, as it can't do flow control.

Upvotes: 1

Related Questions