Flask-Table


NameFlask-Table JSON
Version 0.5.0 PyPI version JSON
download
home_pagehttps://github.com/plumdog/flask_table
SummaryHTML tables for use with the Flask micro-framework
upload_time2017-12-22 19:27:33
maintainer
docs_urlNone
authorAndrew Plummer
requires_python
license
keywords
VCS
bugtrack_url
requirements No requirements were recorded.
Travis-CI
coveralls test coverage No coveralls.
            Flask Table
===========

Because writing HTML is fiddly and all of your tables are basically the
same.

Quick Start
===========

.. code:: python

    # import things
    from flask_table import Table, Col

    # Declare your table
    class ItemTable(Table):
        name = Col('Name')
        description = Col('Description')

    # Get some objects
    class Item(object):
        def __init__(self, name, description):
            self.name = name
            self.description = description
    items = [Item('Name1', 'Description1'),
             Item('Name2', 'Description2'),
             Item('Name3', 'Description3')]
    # Or, equivalently, some dicts
    items = [dict(name='Name1', description='Description1'),
             dict(name='Name2', description='Description2'),
             dict(name='Name3', description='Description3')]

    # Or, more likely, load items from your database with something like
    items = ItemModel.query.all()

    # Populate the table
    table = ItemTable(items)

    # Print the html
    print(table.__html__())
    # or just {{ table }} from within a Jinja template

Which gives something like:

.. code:: html

    <table>
    <thead><tr><th>Name</th><th>Description</th></tr></thead>
    <tbody>
    <tr><td>Name1</td><td>Description1</td></tr>
    <tr><td>Name2</td><td>Description2</td></tr>
    <tr><td>Name3</td><td>Description3</td></tr>
    </tbody>
    </table>

Extra things:
-------------

-  The attribute used for each column in the declaration of the column
   is used as the default thing to lookup in each item.

-  The thing that you pass when you populate the table must:
-  be iterable
-  contain dicts or objects - there's nothing saying it can't contain
   some of each. See ``examples/simple_sqlalchemy.py`` for a database
   example.

-  You can pass attributes to the ``td`` and ``th`` elements by passing
   a dict of attributes as ``td_html_attrs`` or ``th_html_attrs`` when
   creating a Col. Or as ``column_html_attrs`` to apply the attributes
   to both the ``th``\ s and the ``td``\ s. (Any that you pass in
   ``th_html_attrs`` or ``td_html_attrs`` will overwrite any that you
   also pass with ``column_html_attrs``.) See
   examples/column\_html\_attrs.py for more.

-  There are also LinkCol and ButtonCol that allow links and buttons,
   which is where the Flask-specific-ness comes in.

-  There are also DateCol and DatetimeCol that format dates and
   datetimes.

-  Oh, and BoolCol, which does Yes/No.

-  But most importantly, Col is easy to subclass.

Table configuration and options
===============================

The following options configure table-level options:

-  ``thead_classes`` - a list of classes to set on the ``<thead>``
   element.

-  ``no_items`` - a string to display if no items are passed, defaults
   to ``'No Items'``.

-  ``html_attrs`` - a dictionary of attributes to set on the ``<table>``
   element.

-  ``classes`` - a list of strings to be set as the ``class`` attribute
   on the ``<table>`` element.

-  ``table_id`` - a string to set as the ``id`` attribute on the
   ``<table>`` element.

-  ``border`` - whether the ``border`` should be set on the ``<table>``
   element.

These can be set in a few different ways:

a) set when defining the table class

   .. code:: python

       class MyTable
       classes = ['class1', 'class2']

b) passed in the ``options`` argument to ``create_table``.

   .. code:: python

       MyTable = create_table(options={'table_id': 'my-table-id'})

c) passed to the table's ``__init__``

   .. code:: python

       table = MyTable(items, no_items='There is nothing', ...)

Note that a) and b) define an attribute on the table class, but c)
defines an attribute on the instance, so anything set like in c) will
override anything set in a) or b).

Eg:

.. code:: python

    class ItemTable(Table):
        classes = ['myclass']
        name = Col('Name')
    table = ItemTable(items, classes=['otherclass'])

would create a table with ``class="otherclass"``.

Included Col Types
==================

-  ```OptCol`` <#more-about-optcol>`__ - converts values according to a
   dictionary of choices. Eg for turning stored codes into human
   readable text.

-  ```BoolCol`` <#more-about-boolcol>`__ (subclass of OptCol) - converts
   values to yes/no.

-  ```BoolNaCol`` <#more-about-boolnacol>`__ (subclass of BoolCol) -
   converts values to yes/no/na.

-  ```DateCol`` <#more-about-datecol>`__ - for dates (uses
   ``format_date`` from ``babel.dates``).

-  ```DatetimeCol`` <#more-about-datetimecol>`__ - for date-times (uses
   ``format_datetime`` from ``babel.dates``).

-  ```LinkCol`` <#more-about-linkcol>`__ - creates a link by specifying
   an endpoint and url\_kwargs.

-  ```ButtonCol`` <#more-about-buttoncol>`__ (subclass of LinkCol)
   creates a button that posts the the given address.

-  ```NestedTableCol`` <#more-about-nestedtablecol>`__ - allows nesting
   of tables inside columns

More about ``OptCol``
---------------------

When creating the column, you pass some ``choices``. This should be a
dict with the keys being the values that will be found on the item's
attribute, and the values will be the text to be displayed.

You can also set a ``default_key``, or a ``default_value``. The default
value will be used if the value found from the item isn't in the choices
dict. The default key works in much the same way, but means that if your
default is already in your choices, you can just point to it rather than
repeat it.

And you can use ``coerce_fn`` if you need to alter the value from the
item before looking it up in the dict.

More about ``BoolCol``
----------------------

A subclass of ``OptCol`` where the ``choices`` are:

.. code:: python

    {True: 'Yes', False: 'No'}

and the ``coerce_fn`` is ``bool``. So the value from the item is coerced
to a ``bool`` and then looked up in the choices to get the text to
display.

If you want to specify something other than "Yes" and "No", you can pass
``yes_display`` and/or ``no_display`` when creating the column. Eg:

.. code:: python

    class MyTable(Table):
        mybool = BoolCol('myboolcol', yes_display='Affirmative', no_display='Negatory')

More about ``BoolNaCol``
------------------------

Just like ``BoolCol``, except displays ``None`` as "N/A". Can override
with the ``na_display`` argument.

More about ``DateCol``
----------------------

Formats a date from the item. Can specify a ``date_format`` to use,
which defaults to ``'short'``, which is passed to
``babel.dates.format_date``.

More about ``DatetimeCol``
--------------------------

Formats a datetime from the item. Can specify a ``datetime_format`` to
use, which defaults to ``'short'``, which is passed to
``babel.dates.format_datetime``.

More about ``LinkCol``
----------------------

Gives a way of putting a link into a ``td``. You must specify an
``endpoint`` for the url. You should also specify some ``url_kwargs``.
This should be a dict which will be passed as the second argument of
``url_for``, except the values will be treated as attributes to be
looked up on the item. These keys obey the same rules as elsewhere, so
can be things like ``'category.name'`` or ``('category', 'name')``.

The kwarg ``url_kwargs_extra`` allows passing of contants to the url.
This can be useful for adding constant GET params to a url.

The text for the link is acquired in *almost* the same way as with other
columns. However, other columns can be given no ``attr`` or
``attr_list`` and will use the attribute that the column was given in
the table class, but ``LinkCol`` does not, and instead falls back to the
heading of the column. This make more sense for things like an "Edit"
link. You can override this fallback with the ``text_fallback`` kwarg.

Set attributes for anchor tag by passing ``anchor_attrs``:

.. code:: python

    name = LinkCol('Name', 'single_item', url_kwargs=dict(id='id'), anchor_attrs={'class': 'myclass'})

More about ``ButtonCol``
------------------------

Has all the same options as ``LinkCol`` but instead adds a form and a
button that gets posted to the url.

You can pass a dict of attributes to add to the button element with the
``button_attrs`` kwarg.

You can pass a dict of attributes to add to the form element with the
``form_attrs`` kwarg.

You can pass a dict of hidden fields to add into the form element with
the ``form_hidden_fields`` kwargs. The keys will be used as the ``name``
attributes and the values as the ``value`` attributes.

More about ``NestedTableCol``
-----------------------------

This column type makes it possible to nest tables in columns. For each
nested table column you need to define a subclass of Table as you
normally would when defining a table. The name of that Table sub-class
is the second argument to NestedTableCol.

Eg:

.. code:: python

    class MySubTable(Table):
        a = Col('1st nested table col')
        b = Col('2nd nested table col')

    class MainTable(Table):
        id = Col('id')
        objects = NestedTableCol('objects', MySubTable)

Subclassing Col
===============

(Look in examples/subclassing.py for a more concrete example)

Suppose our item has an attribute, but we don't want to output the value
directly, we need to alter it first. If the value that we get from the
item gives us all the information we need, then we can just override the
td\_format method:

.. code:: python

    class LangCol(Col):
        def td_format(self, content):
            if content == 'en_GB':
                return 'British English'
            elif content == 'de_DE':
                return 'German'
            elif content == 'fr_FR':
                return 'French'
            else:
                return 'Not Specified'

If you need access to all of information in the item, then we can go a
stage earlier in the process and override the td\_contents method:

.. code:: python

    from flask import Markup

    def td_contents(self, i, attr_list):
        # by default this does
        # return self.td_format(self.from_attr_list(i, attr_list))
        return Markup.escape(self.from_attr_list(i, attr_list) + ' for ' + item.name)

At present, you do still need to be careful about escaping things as you
override these methods. Also, because of the way that the Markup class
works, you need to be careful about how you concatenate these with other
strings.

Manipulating ``<tr>``\ s
========================

(Look in examples/rows.py for a more concrete example)

Suppose you want to change something about the tr element for some or
all items. You can do this by overriding your table's ``get_tr_attrs``
method. By default, this method returns an empty dict.

So, we might want to use something like:

.. code:: python

    class ItemTable(Table):
        name = Col('Name')
        description = Col('Description')

        def get_tr_attrs(self, item):
            if item.important():
                return {'class': 'important'}
            else:
                return {}

which would give all trs for items that returned a true value for the
``important()`` method, a class of "important".

Dynamically Creating Tables
===========================

(Look in examples/dynamic.py for a more concrete example)

You can define a table dynamically too.

.. code:: python

    TableCls = create_table('TableCls')\
        .add_column('name', Col('Name'))\
        .add_column('description', Col('Description'))

which is equivalent to

.. code:: python

    class TableCls(Table):
        name = Col('Name')
        description = Col('Description')

but makes it easier to add columns dynamically.

For example, you may wish to only add a column based on a condition.

.. code:: python

    TableCls = create_table('TableCls')\
        .add_column('name', Col('Name'))

    if condition:
        TableCls.add_column('description', Col('Description'))

which is equivalent to

.. code:: python

    class TableCls(Table):
        name = Col('Name')
        description = Col('Description', show=condition)

thanks to the ``show`` option. Use whichever you think makes your code
more readable. Though you may still need the dynamic option for
something like

.. code:: python

    TableCls = create_table('TableCls')
    for i in range(num):
        TableCls.add_column(str(i), Col(str(i)))

We can also set some extra options to the table class by passing
``options`` parameter to ``create_table()``:

.. code:: python

    tbl_options = dict(
        classes=['cls1', 'cls2'],
        thead_classes=['cls_head1', 'cls_head2'],
        no_items='Empty')
    TableCls = create_table(options=tbl_options)

    # equals to

    class TableCls(Table):
        classes = ['cls1', 'cls2']
        thead_classes = ['cls_head1', 'cls_head2']
        no_items = 'Empty'

Sortable Tables
===============

(Look in examples/sortable.py for a more concrete example)

Define a table and set its allow\_sort attribute to True. Now all
columns will be default try to turn their header into a link for
sorting, unless you set allow\_sort to False for a column.

You also must declare a sort\_url method for that table. Given a
col\_key, this determines the url for link in the header. If reverse is
True, then that means that the table has just been sorted by that column
and the url can adjust accordingly, ie to now give the address for the
table sorted in the reverse direction. It is, however, entirely up to
your flask view method to interpret the values given to it from this url
and to order the results before giving the to the table. The table
itself will not do any reordering of the items it is given.

.. code:: python

    class SortableTable(Table):
        name = Col('Name')
        allow_sort = True

        def sort_url(self, col_key, reverse=False):
            if reverse:
                direction =  'desc'
            else:
                direction = 'asc'
            return url_for('index', sort=col_key, direction=direction)

The Examples
============

The ``examples`` directory contains a few pieces of sample code to show
some of the concepts and features. They are all intended to be runnable.
Some of them just output the code they generate, but some (just one,
``sortable.py``, at present) actually creates a Flask app that you can
access.

You should be able to just run them directly with ``python``, but if you
have cloned the repository for the sake of dev, and created a
virtualenv, you may find that they generate an import error for
``flask_table``. This is because ``flask_table`` hasn't been installed,
and can be rectified by running something like
``PYTHONPATH=.:./lib/python3.3/site-packages python examples/simple.py``,
which will use the local version of ``flask_table`` including any
changes.

Also, if there is anything that you think is not clear and would be
helped by an example, please just ask and I'll happily write one. Only
you can help me realise which bits are tricky or non-obvious and help me
to work on explaining the bits that need explaining.

Other Things
============

At the time of first writing, I was not aware of the work of
Django-Tables. However, I have now found it and started adapting ideas
from it, where appropriate. For example, allowing items to be dicts as
well as objects.

.. |Build Status| image:: https://travis-ci.org/plumdog/flask_table.svg?branch=master
   :target: https://travis-ci.org/plumdog/flask_table
.. |Coverage Status| image:: https://coveralls.io/repos/plumdog/flask_table/badge.png?branch=master
   :target: https://coveralls.io/r/plumdog/flask_table?branch=master
            

Raw data

            {
    "_id": null,
    "home_page": "https://github.com/plumdog/flask_table",
    "name": "Flask-Table",
    "maintainer": "",
    "docs_url": null,
    "requires_python": "",
    "maintainer_email": "",
    "keywords": "",
    "author": "Andrew Plummer",
    "author_email": "plummer574@gmail.com",
    "download_url": "https://files.pythonhosted.org/packages/5c/f8/c8680277a8a0170d6f4c170dc4525f7869134021549eb84b116a75a24b15/Flask-Table-0.5.0.tar.gz",
    "platform": "",
    "description": "Flask Table\n===========\n\nBecause writing HTML is fiddly and all of your tables are basically the\nsame.\n\nQuick Start\n===========\n\n.. code:: python\n\n    # import things\n    from flask_table import Table, Col\n\n    # Declare your table\n    class ItemTable(Table):\n        name = Col('Name')\n        description = Col('Description')\n\n    # Get some objects\n    class Item(object):\n        def __init__(self, name, description):\n            self.name = name\n            self.description = description\n    items = [Item('Name1', 'Description1'),\n             Item('Name2', 'Description2'),\n             Item('Name3', 'Description3')]\n    # Or, equivalently, some dicts\n    items = [dict(name='Name1', description='Description1'),\n             dict(name='Name2', description='Description2'),\n             dict(name='Name3', description='Description3')]\n\n    # Or, more likely, load items from your database with something like\n    items = ItemModel.query.all()\n\n    # Populate the table\n    table = ItemTable(items)\n\n    # Print the html\n    print(table.__html__())\n    # or just {{ table }} from within a Jinja template\n\nWhich gives something like:\n\n.. code:: html\n\n    <table>\n    <thead><tr><th>Name</th><th>Description</th></tr></thead>\n    <tbody>\n    <tr><td>Name1</td><td>Description1</td></tr>\n    <tr><td>Name2</td><td>Description2</td></tr>\n    <tr><td>Name3</td><td>Description3</td></tr>\n    </tbody>\n    </table>\n\nExtra things:\n-------------\n\n-  The attribute used for each column in the declaration of the column\n   is used as the default thing to lookup in each item.\n\n-  The thing that you pass when you populate the table must:\n-  be iterable\n-  contain dicts or objects - there's nothing saying it can't contain\n   some of each. See ``examples/simple_sqlalchemy.py`` for a database\n   example.\n\n-  You can pass attributes to the ``td`` and ``th`` elements by passing\n   a dict of attributes as ``td_html_attrs`` or ``th_html_attrs`` when\n   creating a Col. Or as ``column_html_attrs`` to apply the attributes\n   to both the ``th``\\ s and the ``td``\\ s. (Any that you pass in\n   ``th_html_attrs`` or ``td_html_attrs`` will overwrite any that you\n   also pass with ``column_html_attrs``.) See\n   examples/column\\_html\\_attrs.py for more.\n\n-  There are also LinkCol and ButtonCol that allow links and buttons,\n   which is where the Flask-specific-ness comes in.\n\n-  There are also DateCol and DatetimeCol that format dates and\n   datetimes.\n\n-  Oh, and BoolCol, which does Yes/No.\n\n-  But most importantly, Col is easy to subclass.\n\nTable configuration and options\n===============================\n\nThe following options configure table-level options:\n\n-  ``thead_classes`` - a list of classes to set on the ``<thead>``\n   element.\n\n-  ``no_items`` - a string to display if no items are passed, defaults\n   to ``'No Items'``.\n\n-  ``html_attrs`` - a dictionary of attributes to set on the ``<table>``\n   element.\n\n-  ``classes`` - a list of strings to be set as the ``class`` attribute\n   on the ``<table>`` element.\n\n-  ``table_id`` - a string to set as the ``id`` attribute on the\n   ``<table>`` element.\n\n-  ``border`` - whether the ``border`` should be set on the ``<table>``\n   element.\n\nThese can be set in a few different ways:\n\na) set when defining the table class\n\n   .. code:: python\n\n       class MyTable\n       classes = ['class1', 'class2']\n\nb) passed in the ``options`` argument to ``create_table``.\n\n   .. code:: python\n\n       MyTable = create_table(options={'table_id': 'my-table-id'})\n\nc) passed to the table's ``__init__``\n\n   .. code:: python\n\n       table = MyTable(items, no_items='There is nothing', ...)\n\nNote that a) and b) define an attribute on the table class, but c)\ndefines an attribute on the instance, so anything set like in c) will\noverride anything set in a) or b).\n\nEg:\n\n.. code:: python\n\n    class ItemTable(Table):\n        classes = ['myclass']\n        name = Col('Name')\n    table = ItemTable(items, classes=['otherclass'])\n\nwould create a table with ``class=\"otherclass\"``.\n\nIncluded Col Types\n==================\n\n-  ```OptCol`` <#more-about-optcol>`__ - converts values according to a\n   dictionary of choices. Eg for turning stored codes into human\n   readable text.\n\n-  ```BoolCol`` <#more-about-boolcol>`__ (subclass of OptCol) - converts\n   values to yes/no.\n\n-  ```BoolNaCol`` <#more-about-boolnacol>`__ (subclass of BoolCol) -\n   converts values to yes/no/na.\n\n-  ```DateCol`` <#more-about-datecol>`__ - for dates (uses\n   ``format_date`` from ``babel.dates``).\n\n-  ```DatetimeCol`` <#more-about-datetimecol>`__ - for date-times (uses\n   ``format_datetime`` from ``babel.dates``).\n\n-  ```LinkCol`` <#more-about-linkcol>`__ - creates a link by specifying\n   an endpoint and url\\_kwargs.\n\n-  ```ButtonCol`` <#more-about-buttoncol>`__ (subclass of LinkCol)\n   creates a button that posts the the given address.\n\n-  ```NestedTableCol`` <#more-about-nestedtablecol>`__ - allows nesting\n   of tables inside columns\n\nMore about ``OptCol``\n---------------------\n\nWhen creating the column, you pass some ``choices``. This should be a\ndict with the keys being the values that will be found on the item's\nattribute, and the values will be the text to be displayed.\n\nYou can also set a ``default_key``, or a ``default_value``. The default\nvalue will be used if the value found from the item isn't in the choices\ndict. The default key works in much the same way, but means that if your\ndefault is already in your choices, you can just point to it rather than\nrepeat it.\n\nAnd you can use ``coerce_fn`` if you need to alter the value from the\nitem before looking it up in the dict.\n\nMore about ``BoolCol``\n----------------------\n\nA subclass of ``OptCol`` where the ``choices`` are:\n\n.. code:: python\n\n    {True: 'Yes', False: 'No'}\n\nand the ``coerce_fn`` is ``bool``. So the value from the item is coerced\nto a ``bool`` and then looked up in the choices to get the text to\ndisplay.\n\nIf you want to specify something other than \"Yes\" and \"No\", you can pass\n``yes_display`` and/or ``no_display`` when creating the column. Eg:\n\n.. code:: python\n\n    class MyTable(Table):\n        mybool = BoolCol('myboolcol', yes_display='Affirmative', no_display='Negatory')\n\nMore about ``BoolNaCol``\n------------------------\n\nJust like ``BoolCol``, except displays ``None`` as \"N/A\". Can override\nwith the ``na_display`` argument.\n\nMore about ``DateCol``\n----------------------\n\nFormats a date from the item. Can specify a ``date_format`` to use,\nwhich defaults to ``'short'``, which is passed to\n``babel.dates.format_date``.\n\nMore about ``DatetimeCol``\n--------------------------\n\nFormats a datetime from the item. Can specify a ``datetime_format`` to\nuse, which defaults to ``'short'``, which is passed to\n``babel.dates.format_datetime``.\n\nMore about ``LinkCol``\n----------------------\n\nGives a way of putting a link into a ``td``. You must specify an\n``endpoint`` for the url. You should also specify some ``url_kwargs``.\nThis should be a dict which will be passed as the second argument of\n``url_for``, except the values will be treated as attributes to be\nlooked up on the item. These keys obey the same rules as elsewhere, so\ncan be things like ``'category.name'`` or ``('category', 'name')``.\n\nThe kwarg ``url_kwargs_extra`` allows passing of contants to the url.\nThis can be useful for adding constant GET params to a url.\n\nThe text for the link is acquired in *almost* the same way as with other\ncolumns. However, other columns can be given no ``attr`` or\n``attr_list`` and will use the attribute that the column was given in\nthe table class, but ``LinkCol`` does not, and instead falls back to the\nheading of the column. This make more sense for things like an \"Edit\"\nlink. You can override this fallback with the ``text_fallback`` kwarg.\n\nSet attributes for anchor tag by passing ``anchor_attrs``:\n\n.. code:: python\n\n    name = LinkCol('Name', 'single_item', url_kwargs=dict(id='id'), anchor_attrs={'class': 'myclass'})\n\nMore about ``ButtonCol``\n------------------------\n\nHas all the same options as ``LinkCol`` but instead adds a form and a\nbutton that gets posted to the url.\n\nYou can pass a dict of attributes to add to the button element with the\n``button_attrs`` kwarg.\n\nYou can pass a dict of attributes to add to the form element with the\n``form_attrs`` kwarg.\n\nYou can pass a dict of hidden fields to add into the form element with\nthe ``form_hidden_fields`` kwargs. The keys will be used as the ``name``\nattributes and the values as the ``value`` attributes.\n\nMore about ``NestedTableCol``\n-----------------------------\n\nThis column type makes it possible to nest tables in columns. For each\nnested table column you need to define a subclass of Table as you\nnormally would when defining a table. The name of that Table sub-class\nis the second argument to NestedTableCol.\n\nEg:\n\n.. code:: python\n\n    class MySubTable(Table):\n        a = Col('1st nested table col')\n        b = Col('2nd nested table col')\n\n    class MainTable(Table):\n        id = Col('id')\n        objects = NestedTableCol('objects', MySubTable)\n\nSubclassing Col\n===============\n\n(Look in examples/subclassing.py for a more concrete example)\n\nSuppose our item has an attribute, but we don't want to output the value\ndirectly, we need to alter it first. If the value that we get from the\nitem gives us all the information we need, then we can just override the\ntd\\_format method:\n\n.. code:: python\n\n    class LangCol(Col):\n        def td_format(self, content):\n            if content == 'en_GB':\n                return 'British English'\n            elif content == 'de_DE':\n                return 'German'\n            elif content == 'fr_FR':\n                return 'French'\n            else:\n                return 'Not Specified'\n\nIf you need access to all of information in the item, then we can go a\nstage earlier in the process and override the td\\_contents method:\n\n.. code:: python\n\n    from flask import Markup\n\n    def td_contents(self, i, attr_list):\n        # by default this does\n        # return self.td_format(self.from_attr_list(i, attr_list))\n        return Markup.escape(self.from_attr_list(i, attr_list) + ' for ' + item.name)\n\nAt present, you do still need to be careful about escaping things as you\noverride these methods. Also, because of the way that the Markup class\nworks, you need to be careful about how you concatenate these with other\nstrings.\n\nManipulating ``<tr>``\\ s\n========================\n\n(Look in examples/rows.py for a more concrete example)\n\nSuppose you want to change something about the tr element for some or\nall items. You can do this by overriding your table's ``get_tr_attrs``\nmethod. By default, this method returns an empty dict.\n\nSo, we might want to use something like:\n\n.. code:: python\n\n    class ItemTable(Table):\n        name = Col('Name')\n        description = Col('Description')\n\n        def get_tr_attrs(self, item):\n            if item.important():\n                return {'class': 'important'}\n            else:\n                return {}\n\nwhich would give all trs for items that returned a true value for the\n``important()`` method, a class of \"important\".\n\nDynamically Creating Tables\n===========================\n\n(Look in examples/dynamic.py for a more concrete example)\n\nYou can define a table dynamically too.\n\n.. code:: python\n\n    TableCls = create_table('TableCls')\\\n        .add_column('name', Col('Name'))\\\n        .add_column('description', Col('Description'))\n\nwhich is equivalent to\n\n.. code:: python\n\n    class TableCls(Table):\n        name = Col('Name')\n        description = Col('Description')\n\nbut makes it easier to add columns dynamically.\n\nFor example, you may wish to only add a column based on a condition.\n\n.. code:: python\n\n    TableCls = create_table('TableCls')\\\n        .add_column('name', Col('Name'))\n\n    if condition:\n        TableCls.add_column('description', Col('Description'))\n\nwhich is equivalent to\n\n.. code:: python\n\n    class TableCls(Table):\n        name = Col('Name')\n        description = Col('Description', show=condition)\n\nthanks to the ``show`` option. Use whichever you think makes your code\nmore readable. Though you may still need the dynamic option for\nsomething like\n\n.. code:: python\n\n    TableCls = create_table('TableCls')\n    for i in range(num):\n        TableCls.add_column(str(i), Col(str(i)))\n\nWe can also set some extra options to the table class by passing\n``options`` parameter to ``create_table()``:\n\n.. code:: python\n\n    tbl_options = dict(\n        classes=['cls1', 'cls2'],\n        thead_classes=['cls_head1', 'cls_head2'],\n        no_items='Empty')\n    TableCls = create_table(options=tbl_options)\n\n    # equals to\n\n    class TableCls(Table):\n        classes = ['cls1', 'cls2']\n        thead_classes = ['cls_head1', 'cls_head2']\n        no_items = 'Empty'\n\nSortable Tables\n===============\n\n(Look in examples/sortable.py for a more concrete example)\n\nDefine a table and set its allow\\_sort attribute to True. Now all\ncolumns will be default try to turn their header into a link for\nsorting, unless you set allow\\_sort to False for a column.\n\nYou also must declare a sort\\_url method for that table. Given a\ncol\\_key, this determines the url for link in the header. If reverse is\nTrue, then that means that the table has just been sorted by that column\nand the url can adjust accordingly, ie to now give the address for the\ntable sorted in the reverse direction. It is, however, entirely up to\nyour flask view method to interpret the values given to it from this url\nand to order the results before giving the to the table. The table\nitself will not do any reordering of the items it is given.\n\n.. code:: python\n\n    class SortableTable(Table):\n        name = Col('Name')\n        allow_sort = True\n\n        def sort_url(self, col_key, reverse=False):\n            if reverse:\n                direction =  'desc'\n            else:\n                direction = 'asc'\n            return url_for('index', sort=col_key, direction=direction)\n\nThe Examples\n============\n\nThe ``examples`` directory contains a few pieces of sample code to show\nsome of the concepts and features. They are all intended to be runnable.\nSome of them just output the code they generate, but some (just one,\n``sortable.py``, at present) actually creates a Flask app that you can\naccess.\n\nYou should be able to just run them directly with ``python``, but if you\nhave cloned the repository for the sake of dev, and created a\nvirtualenv, you may find that they generate an import error for\n``flask_table``. This is because ``flask_table`` hasn't been installed,\nand can be rectified by running something like\n``PYTHONPATH=.:./lib/python3.3/site-packages python examples/simple.py``,\nwhich will use the local version of ``flask_table`` including any\nchanges.\n\nAlso, if there is anything that you think is not clear and would be\nhelped by an example, please just ask and I'll happily write one. Only\nyou can help me realise which bits are tricky or non-obvious and help me\nto work on explaining the bits that need explaining.\n\nOther Things\n============\n\nAt the time of first writing, I was not aware of the work of\nDjango-Tables. However, I have now found it and started adapting ideas\nfrom it, where appropriate. For example, allowing items to be dicts as\nwell as objects.\n\n.. |Build Status| image:: https://travis-ci.org/plumdog/flask_table.svg?branch=master\n   :target: https://travis-ci.org/plumdog/flask_table\n.. |Coverage Status| image:: https://coveralls.io/repos/plumdog/flask_table/badge.png?branch=master\n   :target: https://coveralls.io/r/plumdog/flask_table?branch=master",
    "bugtrack_url": null,
    "license": "",
    "summary": "HTML tables for use with the Flask micro-framework",
    "version": "0.5.0",
    "project_urls": {
        "Homepage": "https://github.com/plumdog/flask_table"
    },
    "split_keywords": [],
    "urls": [
        {
            "comment_text": "",
            "digests": {
                "blake2b_256": "5cf8c8680277a8a0170d6f4c170dc4525f7869134021549eb84b116a75a24b15",
                "md5": "e1d31040efa020013d0867df0bde8828",
                "sha256": "320e5756cd7252e902e03b6cd1087f2c7ebc31364341b482f41f30074d10a770"
            },
            "downloads": -1,
            "filename": "Flask-Table-0.5.0.tar.gz",
            "has_sig": false,
            "md5_digest": "e1d31040efa020013d0867df0bde8828",
            "packagetype": "sdist",
            "python_version": "source",
            "requires_python": null,
            "size": 18048,
            "upload_time": "2017-12-22T19:27:33",
            "upload_time_iso_8601": "2017-12-22T19:27:33.447907Z",
            "url": "https://files.pythonhosted.org/packages/5c/f8/c8680277a8a0170d6f4c170dc4525f7869134021549eb84b116a75a24b15/Flask-Table-0.5.0.tar.gz",
            "yanked": false,
            "yanked_reason": null
        }
    ],
    "upload_time": "2017-12-22 19:27:33",
    "github": true,
    "gitlab": false,
    "bitbucket": false,
    "codeberg": false,
    "github_user": "plumdog",
    "github_project": "flask_table",
    "travis_ci": true,
    "coveralls": false,
    "github_actions": false,
    "requirements": [],
    "lcname": "flask-table"
}
        
Elapsed time: 2.69589s