Last active
July 19, 2019 11:27
-
-
Save sujeetkv/b36a1be5776a6c6229229a9faf9453e8 to your computer and use it in GitHub Desktop.
Generate menu dynamically for flask application
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
from flask_menu import FlaskMenu | |
import check_menu # any function which returns boolean to set menu visibility of particular menu item | |
# create object | |
app_menu = FlaskMenu(children=[ | |
dict( | |
menu_id='dashboard', | |
title='Dashboard', | |
icon='dashboard', | |
endpoint='main.index', | |
is_visible=lambda menu_instance:check_menu(menu_instance), | |
), | |
dict( | |
menu_id='order_management', | |
title='Order Management', | |
icon='list', | |
is_visible=lambda menu_instance:check_menu(menu_instance), | |
children=[ | |
dict( | |
menu_id='order_list', | |
title='Orders', | |
endpoint='orders.index', | |
), | |
dict( | |
menu_id='order_create', | |
title='Create Order', | |
endpoint='orders.create', | |
is_visible=lambda menu_instance:check_menu(menu_instance), | |
), | |
], | |
), | |
]) | |
# load jinja utility extension | |
app.jinja_env.add_extension('jinja2.ext.do') | |
# make this object globally available in template context | |
@app.context_processor | |
def process_template_context(): | |
return dict(app_menu=app_menu) |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<!-- render menu in template --> | |
{% for item in app_menu.children recursive %} | |
<li {% if item.is_active() or item.has_active_child() %} class="active"{% endif %}> | |
{% if item.children %} | |
{% if item.is_visible() and item.has_visible_child() %} | |
<a href="{% if item.endpoint %}{{ url_for(item.endpoint) }}{% else %}javascript:;{% endif %}" data-target="#collapse-{{ item.menu_id }}"> | |
{% if item.icon %}<i class="fa fa-fw fa-{{ item.icon }}"></i> {% endif %}{{ item.title }} | |
</a> | |
<ul id="collapse-{{ item.menu_id }}"> | |
{{ loop(item.children) }} | |
</ul> | |
{% endif %} | |
{% else %} | |
{% if item.is_visible() %} | |
<a href="{% if item.endpoint %}{{ url_for(item.endpoint) }}{% else %}javascript:;{% endif %}"{% if item.is_active() %} class="active"{% endif %}> | |
{% if item.icon %}<i class="fa fa-fw fa-{{ item.icon }}"></i> {% endif %}{{ item.title }} | |
</a> | |
{% endif %} | |
{% endif %} | |
</li> | |
{% endfor %} | |
<!-- set active menu in current template outside any block --> | |
{% do app_menu.set_active('order_list') %} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment