Skip to content

Commit

Permalink
New JavascriptCode function to execute Javascript code like columns.r…
Browse files Browse the repository at this point in the history
…ender (#157)

* New class JavascriptCode to encapsulate JS code

* Add an example with columns.render

* define dt_args after initializing datatables

* rename dt init module

* version date
  • Loading branch information
mwouts committed Jan 31, 2023
1 parent fe27982 commit 29ec54c
Show file tree
Hide file tree
Showing 8 changed files with 70 additions and 25 deletions.
25 changes: 25 additions & 0 deletions docs/advanced_parameters.md
Original file line number Diff line number Diff line change
Expand Up @@ -244,6 +244,31 @@ with pd.option_context("display.float_format", "${:,.2f}".format):
show(pd.Series([i * math.pi for i in range(1, 6)]))
```

## Javascript formatting

Numbers are formatted using Pandas, then are converted back to float to ensure they come in the right order when sorted.
Therefore, to achieve a particular formatting you might have to resort to the
[`columns.render` option](https://datatables.net/examples/advanced_init/column_render.html)
of datatables.

For instance, this [example](https://datatables.net/forums/discussion/61407/how-to-apply-a-numeric-format-to-a-column)
can be ported like this:

```{code-cell}
from itables import JavascriptCode
show(
pd.Series([i * math.pi * 1e4 for i in range(1, 6)]),
columnDefs=[
{
"targets": "_all",
"render": JavascriptCode("$.fn.dataTable.render.number(',', '.', 3, '$')"),
}
],
)
```

## Row order

Since `itables>=1.3.0`, the interactive datatable shows the rows in the same order as the original dataframe:
Expand Down
8 changes: 8 additions & 0 deletions docs/changelog.md
Original file line number Diff line number Diff line change
@@ -1,6 +1,14 @@
ITables ChangeLog
=================

1.4.6 (2023-01-31)
------------------

**Added**
- We have added a new `JavascriptCode` class to encapsulate JS Code.
This will let the user set JS values for some options like `columnDefs.render` ([#154](https://github.com/mwouts/itables/issues/154)).


1.4.5 (2023-01-23)
------------------

Expand Down
9 changes: 8 additions & 1 deletion itables/__init__.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,17 @@
from .javascript import JavascriptFunction, init_notebook_mode, show, to_html_datatable
from .javascript import (
JavascriptCode,
JavascriptFunction,
init_notebook_mode,
show,
to_html_datatable,
)
from .version import __version__

__all__ = [
"__version__",
"to_html_datatable",
"show",
"init_notebook_mode",
"JavascriptCode",
"JavascriptFunction",
]
18 changes: 10 additions & 8 deletions itables/html/datatables_template.html
Original file line number Diff line number Diff line change
Expand Up @@ -7,16 +7,18 @@
{
// Define the table data
const data = [];

// Define the dt_args
let dt_args = {};
dt_args["data"] = data;

// Display the table
$(document).ready(function () {
// [pre-dt-code]
window.__itables_render('#table_id', dt_args);
});
window.initializeDataTable().then(() => {

// Define the dt_args
let dt_args = {};
dt_args["data"] = data;

// [pre-dt-code]
$('#table_id').DataTable(dt_args);
});
})
}
</script>
</div>
9 changes: 9 additions & 0 deletions itables/html/initialize_offline_datatable.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,9 @@
<script type="module">
window.initializeDataTable = async () => {
if ($.prototype.DataTable) {
return;
}
const dt = (await import("dt_src")).default;
dt(window.$);
}
</script>
14 changes: 0 additions & 14 deletions itables/html/itables_render.html

This file was deleted.

10 changes: 9 additions & 1 deletion itables/javascript.py
Original file line number Diff line number Diff line change
Expand Up @@ -87,7 +87,7 @@ def init_notebook_mode(
display(
HTML(
replace_value(
read_package_file("html/itables_render.html"),
read_package_file("html/initialize_offline_datatable.html"),
"dt_src",
"data:text/javascript;base64,{}".format(dt64),
)
Expand Down Expand Up @@ -163,6 +163,8 @@ def json_dumps(obj, eval_functions):
if isinstance(obj, JavascriptFunction):
assert obj.lstrip().startswith("function")
return obj
if isinstance(obj, JavascriptCode):
return obj
if isinstance(obj, str) and obj.lstrip().startswith("function"):
if eval_functions is True:
return obj
Expand Down Expand Up @@ -205,6 +207,12 @@ def __init__(self, value):
), "A Javascript function is expected to start with 'function'"


class JavascriptCode(str):
"""A class that explicitly states that a string is a Javascript code"""

pass


def _datatables_repr_(df=None, tableId=None, **kwargs):
return to_html_datatable(df, tableId, connected=_CONNECTED, **kwargs)

Expand Down
2 changes: 1 addition & 1 deletion itables/version.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,3 @@
"""ITables' version number"""

__version__ = "1.4.5"
__version__ = "1.4.6"

0 comments on commit 29ec54c

Please sign in to comment.