Forum Discussion

james_scee's avatar
12 years ago

How do you call FreeMarker macros on a page?

[Mod Note: This was originally posted as a comment to this TKB article: Creating FreeMarker macros for custom components and endpoints]

 

How do you call them on the page, as I'm trying as via the freemarker code, but to no avail.

 

macro:

 

<#macro m_singular num words> 
<#if (num == 1)> 
<#return words.singular> 
</#if> 
<#return words.plural>
</#macro>   

attempting to call:

 

<@m_singular num=count.value words={"singular":"post","plural":"posts"} />

2 Replies

  • PaoloT's avatar
    PaoloT
    Lithium Alumni (Retired)
    12 years ago

    Hi James,

     

    not sure if your syntax is correct. Have a look at the Freemarker Manual page  - they have an example:

     

    #Example: Macro with parameters:
    
    <#macro test foo bar baaz>
      Test text, and the params: ${foo}, ${bar}, ${baaz}
    </#macro>
    <#-- call the macro: -->
    <@test foo="a" bar="b" baaz=5*5-2/>  
    

     Hope that helps,

  • AdamN's avatar
    AdamN
    Khoros Oracle
    12 years ago

    I think Paolo is right. A macro cannot return a value. The "return" directive for a macro is just used for exiting the macro. If you need to return a value, you can use a function:

    http://freemarker.org/docs/ref_directive_function.html

     

    So you have a couple options...

     

    If you want to use a macro, you can update your macro definition to just output the string instead of returning a value. For example:

    <#macro m_singular num words> 
    <#if (num == 1)> 
    ${words.singular}
    </#if> 
    ${words.plural}
    </#macro>

     Then to call the macro:

    <@m_singular num=2 words={"singular":"post","plural":"posts"} />

     

    If you'd prefer to change to a function instead, it would look something like this:

    <#function m_singular num words> 
    <#if (num == 1)> 
    <#return words.singular> 
    </#if> 
    <#return words.plural>
    </#function>

     And to call the function:

    ${m_singular(2,{"singular":"post","plural":"posts"})}

     

    I hope this helps! If you're still having trouble getting this to work, let us know what error message(s) you're encountering.