Check if %def is empy in mako template

147 views Asked by At

I have a mako template like

<%def name="header()"></%def>

<header class="header">
  ${self.header()}
</header>

that other templates inherit from. Now, some of the templates that inherit will not define a header. In this case I don't want the <header> tag to appear.

How can I check if the def named header was overwritten (or is still empty)?

1

There are 1 answers

0
Tupteq On

You can use built-in capture() function (explained here) to gather output to variable and then check it with % if statement. Here's example generating proper output:

<%def name="header()"></%def>

<%
  h = capture(self.header)
%>
% if h:
<header class="header">
  ${h}
</header>
% endif

It's not very elegant and may slow down your template slightly. But who cares? It solves the problem :)