Skip to content

Commit

Permalink
Add support to double-curly-braces syntax in addition of the vue-like…
Browse files Browse the repository at this point in the history
… syntax for passing arguments to components
  • Loading branch information
jpsca committed Jul 10, 2024
1 parent 377482b commit 78ab068
Show file tree
Hide file tree
Showing 3 changed files with 60 additions and 5 deletions.
2 changes: 1 addition & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@ build-backend = "poetry.core.masonry.api"

[tool.poetry]
name = "jinjax"
version = "0.41"
version = "0.42"
description = "Replace your HTML templates with Python server-Side components"
authors = ["Juan-Pablo Scaletti <[email protected]>"]
license = "MIT"
Expand Down
21 changes: 17 additions & 4 deletions src/jinjax/jinjax.py
Original file line number Diff line number Diff line change
Expand Up @@ -29,7 +29,7 @@
(?P<name>[a-zA-Z@:$_][a-zA-Z@:$_0-9-]*)
(?:
\s*=\s*
(?P<value>".*?"|'.*?')
(?P<value>".*?"|'.*?'|\{\{.*?\}\})
)?
(?:\s+|/|"|$)
"""
Expand Down Expand Up @@ -86,6 +86,8 @@ def _process_tag(self, source: str, match: re.Match) -> str:
tag = match.group("tag")
attrs = (match.group("attrs") or "").strip()
inline = match.group(0).endswith("/>")
lineno = source[:start].count("\n") + 1

logger.debug(f"{tag} {attrs} {'inline' if not inline else ''}")
if inline:
content = ""
Expand All @@ -95,7 +97,7 @@ def _process_tag(self, source: str, match: re.Match) -> str:
if index == -1:
raise TemplateSyntaxError(
message=f"Unclosed component {match.group(0)}",
lineno=source[:start].count("\n") + 1,
lineno=lineno,
name=self._name,
filename=self._filename
)
Expand All @@ -104,6 +106,7 @@ def _process_tag(self, source: str, match: re.Match) -> str:

attrs_list = self._parse_attrs(attrs)
repl = self._build_call(tag, attrs_list, content)

return f"{source[:start]}{repl}{source[end:]}"

def _parse_attrs(self, attrs: str) -> list[tuple[str, str]]:
Expand All @@ -128,9 +131,19 @@ def _build_call(
name = name.lstrip(":")
attrs.append(f'"{name}"=True')
else:
if name.startswith(":"):
name = name.lstrip(":")
# vue-like syntax
if (
name[0] == ":"
and value[0] in ("\"'")
and value[-1] in ("\"'")
):
value = value[1:-1].strip()

# double curly braces syntax
if value[:2] == "{{" and value[-2:] == "}}":
value = value[2:-2].strip()

name = name.lstrip(":")
attrs.append(f'"{name}"={value}')

str_attrs = "**{" + ", ".join([a.replace("=", ":", 1) for a in attrs]) + "}"
Expand Down
42 changes: 42 additions & 0 deletions tests/test_render.py
Original file line number Diff line number Diff line change
Expand Up @@ -857,3 +857,45 @@ def test_auto_load_assets_with_same_name(catalog, folder, autoescape):
""".strip()

assert html == Markup(expected)


def test_vue_like_syntax(catalog, folder):
(folder / "Test.jinja").write_text("""
{#def a, b, c, d #}
{{ a }} {{ b }} {{ c }} {{ d }}
""")
(folder / "Caller.jinja").write_text(
"""<Test :a="2+2" b="2+2" :c="{'lorem': 'ipsum'}" :d="false" />"""
)
html = catalog.render("Caller")
print(html)
expected = """4 2+2 {'lorem': 'ipsum'} False""".strip()
assert html == Markup(expected)


def test_jinja_like_syntax(catalog, folder):
(folder / "Test.jinja").write_text("""
{#def a, b, c, d #}
{{ a }} {{ b }} {{ c }} {{ d }}
""")
(folder / "Caller.jinja").write_text(
"""<Test a={{ 2+2 }} b="2+2" c={{ {'lorem': 'ipsum'} }} d={{ false }} />"""
)
html = catalog.render("Caller")
print(html)
expected = """4 2+2 {'lorem': 'ipsum'} False""".strip()
assert html == Markup(expected)


def test_mixed_syntax(catalog, folder):
(folder / "Test.jinja").write_text("""
{#def a, b, c, d #}
{{ a }} {{ b }} {{ c }} {{ d }}
""")
(folder / "Caller.jinja").write_text(
"""<Test :a={{ 2+2 }} b="{{2+2}}" :c={{ {'lorem': 'ipsum'} }} :d={{ false }} />"""
)
html = catalog.render("Caller")
print(html)
expected = """4 {{2+2}} {'lorem': 'ipsum'} False""".strip()
assert html == Markup(expected)

0 comments on commit 78ab068

Please sign in to comment.