Skip to content

Commit

Permalink
Support auto build titles, rename argument
Browse files Browse the repository at this point in the history
  • Loading branch information
greyli committed Jun 7, 2020
1 parent b61d590 commit 2ad6480
Show file tree
Hide file tree
Showing 2 changed files with 21 additions and 4 deletions.
14 changes: 14 additions & 0 deletions flask_bootstrap/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,6 +24,19 @@ def is_hidden_field_filter(field):
VERSION_POPPER = '1.14.0'


def get_table_titles(data, primary_key, primary_key_title):
"""Detect and build the table titles tuple from ORM object, currently only support SQLAlchemy.
.. versionadded:: 1.4.0
"""
titles = []
for k in data[0].__table__.columns._data.keys():
if not k.startswith('_'):
titles.append((k, k.replace('_', ' ').title()))
titles[0] = (primary_key, primary_key_title)
return titles


class Bootstrap(object):
def __init__(self, app=None):
if app is not None:
Expand All @@ -42,6 +55,7 @@ def init_app(self, app):
app.jinja_env.globals['bootstrap'] = self
app.jinja_env.globals['bootstrap_is_hidden_field'] = \
is_hidden_field_filter
app.jinja_env.globals['get_table_titles'] = get_table_titles
app.jinja_env.add_extension('jinja2.ext.do')
# default settings
app.config.setdefault('BOOTSTRAP_SERVE_LOCAL', False)
Expand Down
11 changes: 7 additions & 4 deletions flask_bootstrap/templates/bootstrap/table.html
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
{% macro render_table(titles, data, primary_key='id', caption=None, table_classes=None, header_classes=None, is_responsive=False, responsive_class='table-responsive') %}
{% if is_responsive %}
{% macro render_table(data, titles=None, primary_key='id', primary_key_title='#', caption=None, table_classes=None, header_classes=None, responsive=False, responsive_class='table-responsive') %}
{% if not titles %}
{% set titles = get_table_titles(data, primary_key, primary_key_title) %}
{% endif %}
{% if responsive %}
<div class="{{ responsive_class }}">
{% endif %}
<table class="table{% if table_classes %}{{ ' ' + table_classes }}{% endif %}">
Expand Down Expand Up @@ -27,7 +30,7 @@
{% endfor %}
</tbody>
</table>
{% if is_responsive %}
{% if responsive %}
</div>
{% endif %}
{% endmacro %}
{% endmacro %}

0 comments on commit 2ad6480

Please sign in to comment.