Skip to content

Instantly share code, notes, and snippets.

@tyler-sommer
Created March 21, 2013 23:05
Show Gist options
  • Save tyler-sommer/5217621 to your computer and use it in GitHub Desktop.
Save tyler-sommer/5217621 to your computer and use it in GitHub Desktop.
This abuse of the twig templating engine can be used to generate menus given a fairly nice declaration syntax. Currently, it will generate a semi customized bootstrap menu
{% block subnav %}
{# This is how you declare a menu #}
{% include '::subnav.html.twig' with { pages: [
{ name: 'Manage', dropdown: [
{ route: 'customers', name: 'Customers' },
{ route: 'orders', name: 'Orders' },
{ route: 'chargebacks', name:'Chargebacks', role: 'ROLE_ADMIN' }
] },
{ route: 'settings', name: 'Settings' },
{ route: 'sales_report', name: 'Sales Report', role: 'ROLE_ADMIN' },
{ route: 'today_report', name: 'Today Report', params: { date: 'today' }, role: 'ROLE_ADMIN' }
] } %}
{% endblock %}
<ul class="nav nav-pills {{ class|default }}">
{% for route,name in pages|default([]) %}
{% if name|keys|length > 0 %}
{% set route = name.route|default %}
{% set params = name.params|default({}) %}
{% set role = name.role|default %}
{% set class = name.class|default %}
{% set anchor_class = name.anchor_class|default %}
{% set dropdown = name.dropdown|default %}
{% set name = name.name %}
{% endif %}
{% if dropdown|default %}
{% set anchor_class = anchor_class|default ~ ' dropdown-toggle' %}
{% endif %}
{% if not role|default or is_granted(role) %}
{% set class = (is_current_route(route) ? ' active' : '') %}
<li class="{{ class }}">
<a class="{{ anchor_class|default }}"
{% if dropdown|default %}
data-toggle="dropdown"
href="#"
{% else %}
href="{{ path(route, params|default([])) }}"
{% endif %}
{# I'm so ashamed. Next to this is the end of the opening 'a' tag #}>
{{ name }}
{% if dropdown|default %}
<i class="caret"></i>
{% endif %}
</a>
{% if dropdown|default %}{% include '::subnav_dropdown.html.twig' with { dropdown: dropdown } %}{% endif %}
</li>
{% endif %}
{% endfor %}
</ul>
<ul class="dropdown-menu">
{% for route,name in dropdown|default([]) %}
{% if name|keys|length > 0 %}
{% set route = name.route %}
{% set params = name.params|default({}) %}
{% set role = name.role|default %}
{% set class = name.class|default %}
{% set anchor_class = name.anchor_class|default %}
{% set name = name.name %}
{% endif %}
{% if not role|default() or is_granted(role) %}
{% set class = (is_current_route(route) ? ' active' : '') %}
<li class="{{ class }}"><a href="{{ path(route, params|default([])) }}" class="{{ anchor_class|default }}">{{ name }}</a></li>
{% endif %}
{% endfor %}
</ul>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment