Skip to content

Commit

Permalink
Bugfix: accept jinja style templates w/period
Browse files Browse the repository at this point in the history
  • Loading branch information
OleJoik committed Jun 11, 2024
1 parent bebe80e commit 1f93e2e
Show file tree
Hide file tree
Showing 2 changed files with 52 additions and 3 deletions.
16 changes: 13 additions & 3 deletions htpy/html2htpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -186,19 +186,23 @@ def html2htpy(html: str, shorthand_id_class: bool = False, format: bool = False)
def _convert_data_to_string(data: str):
_data = str(data)

is_multiline = "\n" in _data

_data = _data.replace("\n", "")

# escape unescaped dblquote: " -> \"
_data = re.compile(r'(?<![\\])"').sub('\\"', _data)

template_string_pattern = re.compile(r"\{\{\s*(\w+)\s*\}\}")
template_string_pattern = re.compile(r"\{\{\s*[\w\.]+\s*\}\}")

has_jinja_pattern = re.search(template_string_pattern, _data)
if has_jinja_pattern:
# regex replaces these 3 cases:
# {{ var }} -> { var }
# {{ var.xx }} -> { var.xx }
# { -> {{
# } -> }}
template_string_replace_pattern = re.compile(
r"(\{\{\s*(\w+)\s*\}\}|(?<![\{]){(?![\{])|(?<![\}])}(?![\}]))"
r"(\{\{\s*[\w\.]+\s*\}\}|(?<![\{]){(?![\{])|(?<![\}])}(?![\}]))"
)

def replacer(match: re.Match[str]):
Expand All @@ -213,8 +217,14 @@ def replacer(match: re.Match[str]):
return "}}"

_data = template_string_replace_pattern.sub(replacer, _data)
if is_multiline:
_data = '""' + _data + '""'

_data = 'f"' + _data + '"'
else:
if is_multiline:
_data = '""' + _data + '""'

_data = '"' + _data + '"'

return _data
Expand Down
39 changes: 39 additions & 0 deletions tests/test_html2htpy.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,6 +84,45 @@ def test_convert_f_string_escaping():
assert actual == expected


def test_convert_f_string_escaping_complex():
input = """
<body>
<h1>{{ heading }}</h1>
<p>Welcome to our cooking site, {{ user.name }}!</p>
<h2>Recipe of the Day: {{ recipe.name }}</h2>
<p>{{ recipe.description }}</p>
<h3>Instructions:</h3>
<ol>
{% for step in recipe.steps %}
<li>{{ step }}</li>
{% endfor %}
</ol>
</body>
"""

actual = html2htpy(input, format=True)
expected = textwrap.dedent(
"""\
body[
h1[f"{ heading }"],
p[f"Welcome to our cooking site, { user.name }!"],
h2[f"Recipe of the Day: { recipe.name }"],
p[f"{ recipe.description }"],
h3["Instructions:"],
ol[
\"\"\" {% for step in recipe.steps %} \"\"\",
li[f"{ step }"],
\"\"\" {% endfor %} \"\"\",
],
]
"""
)

assert actual == expected


def test_convert_script_style_tags():
input = """
<script type="text/javascript">alert('This is a script');</script>
Expand Down

0 comments on commit 1f93e2e

Please sign in to comment.