templateszotonic

How do you access the menu model from a Zotonic template?


I want to write my own style of menu, but I would prefer to do it in the templates rather than making my own menu scomp.

I basically want to be able to do something like:

{% if m.menu %}
  <ul>
  {% for top_level_id in m.menu %}
    {% with m.rsc[top_level_id] as top_level %}
      <li><a href="{{ top_level.page_url }}">{{ top_level.title }}</a>
      {% if top_level.menu %}
        <ul>
        {% for mid_level_id in top_level.menu %}
          {% with m.rsc[mid_level_id] as mid_level %}
            <li><a href="{{ midlevel.page_url }}">{{ mid_level.title }}</a></li>
          {% endwith %}
        {% endfor %}
        </ul>
      {% endif %}
      </li>
    {% endwith %}
  {% endfor %}
  </ul>
{% endif %}

How do you access the menu model from a Zotonic template?


Solution

  • To add to my previous answer. The standard _menu.tpl receives a list with all menu items. This list is the result of a depth-first tree walk of the complete menu. Every menu is a record with

    {MenuRscId, DepthOfMenu, NrInSubMenu, HasSubMenuFlag}
    

    Where the top level menu has a depth of 1 and the first menu item in a menu has a nr of 1.

    All menu items that the current user is not allowed to see are filtered out.

    The code of the default template:

    <ul id="{{ id_prefix }}navigation" class="clearfix at-menu do_superfish">
    {% for mid,depth,nr,has_sub in menu %}
      {% if not mid %}{% if depth > 1 %}</ul></li>{% endif %}
      {% else %}
         {% if nr == 1 and not forloop.first %}<ul{% if mid|member:path %} class="onpath"{% endif %}>{% endif %}
         <li id="{{ id_prefix }}nav-item-{{nr}}" 
             class="{% if is_first %}first {% endif %}{% if is_last %}last{% endif %}">
             <a href="{{ m.rsc[mid].page_url }}" 
                class="{{ m.rsc[mid].name }}{% if mid == id %} current{% else %}{% if mid|member:path %} onpath{% endif %}{% endif %}">{{ m.rsc[mid].short_title|default:m.rsc[mid].title }}</a>
       {% if not has_sub %}</li>{% endif %}
     {% endif %}
    {% endfor %}
    {% if forloop.last %}{% include "_menu_extra.tpl" %}{% endif %}
    </ul>