Skip to content

Commit

Permalink
Merge pull request #95 from cmason3/v1.20.0
Browse files Browse the repository at this point in the history
V1.20.0
  • Loading branch information
cmason3 authored May 8, 2024
2 parents f15553c + 2408063 commit 3ba9240
Show file tree
Hide file tree
Showing 3 changed files with 88 additions and 1 deletion.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,8 @@
## CHANGELOG

### [1.20.0] - May 8, 2024
- Added support for `jinjafx.tabulate()` to produce GitHub Markdown style tables from `data.csv`

### [1.19.3] - April 22, 2024
- Added an optional `row` argument to `jinjafx.counter()` to allow the current row to be overridden

Expand Down Expand Up @@ -522,6 +525,7 @@ Updated `to_yaml` and `to_nice_yaml` to use `SafeDumper`
- Initial release


[1.20.0]: https://github.com/cmason3/jinjafx/compare/v1.19.3...v1.20.0
[1.19.3]: https://github.com/cmason3/jinjafx/compare/v1.19.2...v1.19.3
[1.19.2]: https://github.com/cmason3/jinjafx/compare/v1.19.1...v1.19.2
[1.19.1]: https://github.com/cmason3/jinjafx/compare/v1.18.7...v1.19.1
Expand Down
35 changes: 35 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -578,6 +578,41 @@ This variable will contain the total number of rows within the data.

This function is used to access all the row and column data that JinjaFx is currently traversing through. The first row (0) will contain the header row with subsequent rows containing the row data - it is accessed using `jinjafx.data(row, col)`. If you wish to access the columns via their case-sensitive name then you can also use `jinjafx.data(row, 'FIELD')`. The `row` argument is mandatory, but if you omit the `col` argument then it will return the whole row as a list.

- <code><b>jinjafx.tabulate(datarows</b>: Optional[List[List[String]]]<b>, *, cols</b>: Optional[List[String]]<b>, colons</b>: Optional[Boolean]<b>=False)</b> -> String</code>

This function will produce a GitHub Markdown styled table using either the provided `datarows` variable, or (if omitted) using the data from `data.csv`, e.g:

```jinja2
{{ jinjafx.tabulate([["A", "B", "C"], ["1", "2", "3"], ["4", "5", "6"]]) }}
```

This will produce the following table:

```
| A | B | C |
| - | - | - |
| 1 | 2 | 3 |
| 4 | 5 | 6 |
```

The first row will always be used as the header row, which matches the behaviour of JinjaFx with respect to `data.csv`. You can also change the order of the columns or decide to only include some of the columns using the `cols` argument, e.g:


```jinja2
{{ jinjafx.tabulate([["A", "B", "C"], ["1", "2", "3"], ["4", "5", "6"]], cols=["C", "A"]) }}
```

This will produce the following table:

```
| C | A |
| - | - |
| 3 | 1 |
| 6 | 4 |
```

All columns are left aligned, except if the column value is of type `int` or `float` (`data.csv` uses `:int` and `:float` syntax to force this) and then they are right aligned. At this point you can't change this, but if you wish to include the `:` as used by GitHub Markdown to force the alignment, you can set `colons` to `True`.

- <code><b>jinjafx.expand(value</b>: String<b>)</b> -> List[String]</code>

This function is used to expand a string that contains static character classes (i.e. `[0-9]`), static groups (i.e. `(a|b)`) or active counters (i.e. `{ start-end:increment }`) into a list of all the different permutations. You are permitted to use as many classes, groups or counters within the same string - if it doesn't detect any classes, groups or counters within the string then the "string" will be returned as the only list element. Character classes support "A-Z", "a-z" and "0-9" characters, whereas static groups allow any string of characters (including static character classes). If you wish to include "[", "]", "(", ")", "{" or "}" literals within the string then they will need to be escaped.
Expand Down
50 changes: 49 additions & 1 deletion jinjafx.py
Original file line number Diff line number Diff line change
Expand Up @@ -31,7 +31,7 @@
from cryptography.hazmat.primitives.ciphers.modes import CTR
from cryptography.exceptions import InvalidSignature

__version__ = '1.19.3'
__version__ = '1.20.0'

__all__ = ['JinjaFx', 'Vault']

Expand Down Expand Up @@ -680,6 +680,7 @@ def jinjafx(self, template, data, gvars, output, exts_dirs=None, sandbox=False):
'first': self.__jfx_first,
'last': self.__jfx_last,
'fields': self.__jfx_fields,
'tabulate': self.__jfx_tabulate,
'data': self.__jfx_data,
'setg': self.__jfx_setg,
'getg': self.__jfx_getg,
Expand Down Expand Up @@ -1125,6 +1126,53 @@ def __jfx_fields(self, field=None, ffilter={}):
return field_values


def __jfx_tabulate(self, datarows=None, *, cols=None, colons=False):
colwidth = []
colmap = []
offset = 0
o = ''

if datarows is None:
datarows = self.__g_datarows
offset = 1

if len(datarows) > 1:
if not cols:
colmap = list(range(len(datarows[0])))

else:
for c in cols:
try:
colmap.append(datarows[0].index(c))

except Exception:
raise JinjaFx.TemplateError(f'invalid column "{c}" passed to jinjafx.tabulate()')

colalign = [["<", ":", " "]] * len(datarows[0])
coltype = [0] * len(datarows[0])

for c in range(len(datarows[0])):
colwidth.append(len(datarows[0][c]))

for r in range(1, len(datarows)):
for c in range(offset, len(datarows[r])):
coltype[c - offset] |= (1<<(isinstance(datarows[r][c], (int, float))))
if colwidth[c - offset] < len(str(datarows[r][c])):
colwidth[c - offset] = len(str(datarows[r][c]))

for c, t in enumerate(coltype):
if t == 2:
colalign[c] = [">", " ", ":"]

o = "| " + " | ".join([f"{datarows[0][c]:{colalign[c][0]}{colwidth[c]}}" for c in colmap]) + " |\n"
o += "|" + "|".join([f"{colalign[c][1] if colons else ' '}{'-' * colwidth[c]}{colalign[c][2] if colons else ' '}" for c in colmap]) + "|\n"

for r in range(1, len(datarows)):
o += "| " + " | ".join([f"{datarows[r][c + offset]:{colalign[c][0]}{colwidth[c]}}" for c in colmap]) + " |\n"

return o.strip()


def __jfx_data(self, row, col=None):
if self.__g_datarows:
if isinstance(col, str):
Expand Down

0 comments on commit 3ba9240

Please sign in to comment.