Search code examples
freemarker

Check for freemarker variable set in child in the base template


I am using freemarker to render my frontend.

This is an extract of my base.ftlh that I use in my pages as a layout. A lot of pages have a header in a similar style therefore they can set the banner icon and the texts for themselves. However, some pages should not have this header, and I want to define a variable like just a boolean header to only render this part if it is set to true, which should be the default.

<#-- Application Main Content - Start -->
<div class="content-grid">
    <#if header!true>
        <div class="section-banner">
            <#if title_banner??>
                <img class="section-banner-icon" src="<@title_banner />" alt="badges-icon">
            </#if>
            <#if title??>
                <p class="section-banner-title"><@title /></p>
            </#if>
            <#if subtitle??>
                <p class="section-banner-text"><@subtitle /></p>
            </#if>
        </div>
    </#if>
    <#if page_body??>
        <@page_body/>
    </#if>
</div>

This is the top of one of my pages profile.ftlh where I want to use the base and tell it to not use the header:

<#include  "/base.ftlh">

<#macro page_title>
    Profil-Suche
</#macro>

<#assign header = false>

<#macro page_body>
    ...

However, this does not work and my header variable I set in my profile.ftlh is completely ignored... How can I achieve this? I'd rather not put the header manually in every page that needs it, I'd prefer it to stay in the base.


Solution

  • The problem is that you are including base.ftl before setting the header variable. Instead, do that #include as the very last thing.

    Note that like in many languages, subroutines (defined with #function/#macro) can be called before reaching the defining statements, so that's why that worked. But assignments can't do such a trick. So it's just cleaner if you do everything before including base.ftl.