Skip to content

Allow whitespace characters within component regex #96

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 9 commits into from
Sep 19, 2022
Merged
4 changes: 4 additions & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -28,6 +28,10 @@ Using the following categories, list your changes in this order:
- `use_query` hook for fetching database values.
- `use_mutation` hook for modifying database values.

### Fixed

- IDOM preloader is no longer sensitive to whitespace within template tags.

## [1.1.0] - 2022-07-01

### Added
Expand Down
22 changes: 18 additions & 4 deletions src/django_idom/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,8 +13,19 @@
from django_idom.config import IDOM_REGISTERED_COMPONENTS


COMPONENT_REGEX = re.compile(r"{% *component +((\"[^\"']*\")|('[^\"']*'))(.*?)%}")
_logger = logging.getLogger(__name__)
_component_tag = r"(?P<tag>component)"
_component_path = r"(?P<path>(\"[^\"'\s]+\")|('[^\"'\s]+'))"
_component_kwargs = r"(?P<kwargs>(.*?|\s*?)*)"
COMPONENT_REGEX = re.compile(
r"{%\s*"
+ _component_tag
+ r"\s*"
+ _component_path
+ r"\s*"
+ _component_kwargs
+ r"\s*%}"
)


def _register_component(full_component_name: str) -> None:
Expand Down Expand Up @@ -102,11 +113,14 @@ def _get_components(self, templates: set[str]) -> set[str]:
for template in templates:
with contextlib.suppress(Exception):
with open(template, "r", encoding="utf-8") as template_file:
match = COMPONENT_REGEX.findall(template_file.read())
if not match:
regex_iterable = COMPONENT_REGEX.finditer(template_file.read())
if not regex_iterable:
continue
components.update(
[group[0].replace('"', "").replace("'", "") for group in match]
[
match.groupdict()["path"].replace('"', "").replace("'", "")
for match in regex_iterable
]
)
if not components:
_logger.warning(
Expand Down
13 changes: 13 additions & 0 deletions tests/test_app/tests/test_regex.py
Original file line number Diff line number Diff line change
Expand Up @@ -13,6 +13,14 @@ def test_component_regex(self):
r"{% component 'my.component' %}",
r'{% component "my.component" class="my_thing" %}',
r'{% component "my.component" class="my_thing" attr="attribute" %}',
r"""{%

component
"my.component"
class="my_thing"
attr="attribute"

%}""", # noqa: W291
}:
self.assertRegex(component, COMPONENT_REGEX)

Expand All @@ -26,5 +34,10 @@ def test_component_regex(self):
r"{%%}",
r" ",
r"",
r'{% component " my.component " %}',
r"""{% component "my.component
" %}""",
r'{{ component """ }}',
r'{{ component "" }}',
}:
self.assertNotRegex(fake_component, COMPONENT_REGEX)