Skip to content

Commit

Permalink
Merge pull request #69 from timvink/add_support_for_indentation_in_ma…
Browse files Browse the repository at this point in the history
…cros

Add support for fixing indentation in jinja
  • Loading branch information
timvink authored Aug 15, 2024
2 parents 9f6b419 + 572b702 commit 5dcaeca
Show file tree
Hide file tree
Showing 6 changed files with 106 additions and 5 deletions.
45 changes: 45 additions & 0 deletions docs/howto/use_jinja2.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,3 +24,48 @@ Now you can do cool things like dynamically load a list of tables:
{% endfor %}

```

## Indented content like content tabs

If you inserted content has multiple lines, then indentation will be not be retained beyond the first line. This means things like [content tabs](https://squidfunk.github.io/mkdocs-material/reference/content-tabs/#usage) will not work as expected.

To fix that, you can use the custom _filter_ `add_indendation` (a filter add to `macros` by `table-reader` plugin). For example:

=== "index.md"

```jinja
{% set table_names = ["basic_table.csv","basic_table2.csv"] %}
{% for table_name in table_names %}

=== "{{ table_name }}"

{ { read_csv(table_name) | add_indentation(spaces=4) }}

{% endfor %}
```

=== "mkdocs.yml"

```yaml
site_name: test git_table_reader site
use_directory_urls: true

theme:
name: material

plugins:
- search
- macros
- table-reader

markdown_extensions:
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true
```

!!! note "Note the space in { {"

To avoid the tables being inserted into the code example, we replaced `{{` with `{ {`.
If you copy this example, make sure to fix.

33 changes: 31 additions & 2 deletions mkdocs_table_reader_plugin/markdown.py
Original file line number Diff line number Diff line change
Expand Up @@ -46,12 +46,41 @@ def convert_to_md_table(df: pd.DataFrame, markdown_kwargs: Dict) -> str:
return df.to_markdown(**markdown_kwargs)


def fix_indentation(leading_spaces: str, text: str) -> str:
def add_indentation(text: str, *, spaces: int = 0, tabs: int = 0) -> str:
"""
Adds indentation to a text.
Args:
leading_spaces (str): Indentation to add
spaces (int): Indentation to add in spaces
tabs (int): Indentation to add in tabs
text (str): input text
Returns:
str: fixed text
"""
if spaces and tabs:
raise ValueError("You can only specify either spaces or tabs, not both.")
if spaces:
indentation = " " * spaces
elif tabs:
indentation = "\t" * tabs
else:
indentation = ""

fixed_lines = []
for line in text.split("\n"):
fixed_lines.append(textwrap.indent(line, indentation))
text = "\n" + "\n".join(fixed_lines) + "\n"

return text


def fix_indentation(text: str, *, leading_spaces: str) -> str:
"""
Adds indentation to a text.
Args:
leading_spaces (str): Indentation to add in actual spaces, e.g. " " for 4 spaces
text (str): input text
Returns:
Expand Down
9 changes: 7 additions & 2 deletions mkdocs_table_reader_plugin/plugin.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@

from mkdocs_table_reader_plugin.safe_eval import parse_argkwarg
from mkdocs_table_reader_plugin.readers import READERS
from mkdocs_table_reader_plugin.markdown import fix_indentation
from mkdocs_table_reader_plugin.markdown import fix_indentation, add_indentation

logger = get_plugin_logger("table-reader")

Expand Down Expand Up @@ -73,6 +73,11 @@ def on_config(self, config, **kwargs):
config.plugins["macros"].macros.update(self.readers)
config.plugins["macros"].variables["macros"].update(self.readers)
config.plugins["macros"].env.globals.update(self.readers)

config.plugins["macros"].filters.update({"add_indentation": add_indentation})
config.plugins["macros"].variables["filters"].update({"add_indentation": add_indentation})
config.plugins["macros"].env.filters.update({"add_indentation": add_indentation})

self.external_jinja_engine = True
else:
self.external_jinja_engine = False
Expand Down Expand Up @@ -144,7 +149,7 @@ def on_page_markdown(self, markdown, page, config, files, **kwargs):
# You might insert multiple CSVs with a single reader like read_csv
# Because of the replacement, the next occurrence will be the first match for .sub() again.
# This is always why when allow_missing_files=True we replaced the input tag.
markdown_table = fix_indentation(leading_spaces, markdown_table)
markdown_table = fix_indentation(leading_spaces=leading_spaces, text=markdown_table)
markdown = tag_pattern.sub(markdown_table, markdown, count=1)

return markdown
2 changes: 1 addition & 1 deletion setup.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@

setup(
name="mkdocs-table-reader-plugin",
version="3.0.0",
version="3.0.1",
description="MkDocs plugin to directly insert tables from files into markdown.",
long_description=long_description,
long_description_content_type="text/markdown",
Expand Down
14 changes: 14 additions & 0 deletions tests/fixtures/jinja/docs/index.md
Original file line number Diff line number Diff line change
Expand Up @@ -13,3 +13,17 @@ This is a table that we load from the docs folder, because we set `data_path` to
{{ read_csv(table_name) }}

{% endfor %}


## Now with tabs


{% for table_name in table_names %}

=== "{{ table_name }}"

{{ read_csv(table_name) | add_indentation(spaces=4) }}


{% endfor %}

8 changes: 8 additions & 0 deletions tests/fixtures/jinja/mkdocs.yml
Original file line number Diff line number Diff line change
@@ -1,7 +1,15 @@
site_name: test git_table_reader site
use_directory_urls: true

theme:
name: material

plugins:
- search
- macros
- table-reader

markdown_extensions:
- pymdownx.superfences
- pymdownx.tabbed:
alternate_style: true

0 comments on commit 5dcaeca

Please sign in to comment.