How do you only show children of "active" parent in a Structure section's nav? I've got a Structure section where the top level is the main menu. The submenu consists of the children of the active main menu item. This works well.

For the submenu, I'm using this code:

{% set mainEntry = craft.entries.slug(craft.request.getSegment(1)).first() %}
{% set subnav = craft.entries.descendantOf(mainEntry) %}

&lt;ul&gt;
{% nav page in subnav %}
  &lt;li{% if page.slug == craft.request.getSegment(page.level) %} class="active"{% endif %}&gt;
    {{ page.getLink() }}
    {% ifchildren %}
      &lt;ul&gt;
        {% children %}
      &lt;/ul&gt;
    {% endifchildren %}
  &lt;/li&gt;
{% endnav %}
&lt;/ul&gt;


...which shows all children of each page.

How can I only show the children of the active parent? I've tried to wrap the ifchildren block inside another if statement (the same I used to set the class="active" to the &lt;li&gt;), but that results in a Template error:


  Unexpected tag name "ifchildren" (expecting closing tag for the "if" tag defined near line x)


Putting that if statement inside the ifchildren block also throws a template error.

PS. With the current HTML output, I could also just use CSS to hide/show the &lt;ul&gt;s based on the .active class, but I'd still like to know how to generate that tree without the need for  a CSS workaround.
A recursive macro will help you get around the limitations of ifchildren (which P&amp;T will hopefully resolve soon), as follows:

{% set mainEntry = craft.entries.slug(craft.request.getSegment(1)).first() %}
{% set subnav = craft.entries.descendantOf(mainEntry).level(2) %}

{% macro recursiveChildren(page) %}
  {% if page.hasDescendants and page.slug == craft.request.getSegment(page.level) %}
    &lt;ul&gt;
      {% for subpage in page.children %}
          &lt;li{% if subpage.slug == craft.request.getSegment(subpage.level) %} class="active"{% endif %}&gt;
            {{ subpage.link }}
            {{ _self.recursiveChildren(subpage) }}
          &lt;/li&gt;
      {% endfor %}
    &lt;/ul&gt;
  {% endif %}
{% endmacro %}

&lt;ul&gt;
{% for page in subnav %}
  &lt;li{% if page.slug == craft.request.getSegment(page.level) %} class="active"{% endif %}&gt;
    {{ page.link }}
    {{ _self.recursiveChildren(page) }}
  &lt;/li&gt;
{% endfor %}
&lt;/ul&gt;


More on macros here.