Skip to content

Added if statement modification #1

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

Open
wants to merge 8 commits into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from 3 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

## Description

Modifies the HTML content of a file to replace all <link> tags' href attributes, all <script> tags' src attributes, and all <img> src attributes by default, also provides support for custom modification of tags and attribute with Django template tags, and adds {% load static %} to the beginning of the file.
Modifies the HTML content of a file to replace all <link> tags' href attributes, all <script> tags' src attributes, and all <img> src attributes by default, also provides support for custom modification of tags and attribute with Django template tags, and adds {% load static %} to the beginning of the file, Also add if.


## Installation
Expand Down Expand Up @@ -52,6 +52,10 @@ Suppose you have an HTML file named index.html that looks like this:
<body>
<h1>Hello, World!</h1>
<img src="image.png">
<div if="error_message">
{{ error_message }}
<button type="button"></button>
</div>
</body>
</html>
```
Expand All @@ -78,12 +82,19 @@ will modify the file to look like this:
<body>
<h1>Hello, World!</h1>
<img src="{% static 'image.png' %}">
{% if error_message %}
<div>
{{ error_message }}
<button type="button">
</button>
</div>
{% endif %}
</body>
</html>
```

Here, the <link>, <script>, and <img> tags' href and src attributes have been replaced with Django template tags, and {% load static %} has been added to the beginning of the file.

Also every element with if attribute will be wrap with if tag, with the value of the attribute is the condition.
# Parameters

- file (str): The path to the input HTML file.
Expand Down
106 changes: 83 additions & 23 deletions html2django/djangohtml.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,13 @@
from bs4 import BeautifulSoup

def djangoify(file: str,img: bool = False ,custom_tag: str = None,custom_attr: str = None,custom_value: str = None) -> None:
def djangoify(file: str,img: bool = False ,custom_tag: str = None,custom_attr: str = None,custom_value: str = None, edit_form:bool = True, edit_a:bool = True) -> None:

"""
Modifies the HTML content of a file to replace all <link> tags' href attributes, all <script> tags' src attributes and
all <img> src attributes by default,also provides support for custom modification of tags and attribute
with Django template tags, and adds "{% load static %}" to the beginning of the file.
with Django template tags, and adds "{% load static %}" to the beginning of the file, Add django if statements to each element
that have if attribute with the val of the attribute is the condition.


Parameters:
- file (str): The path to the input HTML file.
Expand All @@ -20,16 +22,16 @@ def djangoify(file: str,img: bool = False ,custom_tag: str = None,custom_attr: s
Raises:
FileNotFoundError: If the input file cannot be found or accessed.
"""

try:
with open(file, 'r') as f:
readhtml = f.readlines()

if readhtml[0] == "{% load static %}\n":
original_html = "".join(readhtml)
else:
original_html = "{% load static %}" + "".join(readhtml)

except FileNotFoundError:
print(f"\nThe path or name of {file} is not correct.\n")
return 1
Expand All @@ -40,44 +42,102 @@ def djangoify(file: str,img: bool = False ,custom_tag: str = None,custom_attr: s
script = soup.find_all('script')
img = soup.find_all('img')
custom = soup.find_all(custom_tag)

elements_with_if = soup.find_all(attrs={"if": True})
elements_with_for = soup.find_all(attrs={"for": True})

for tag in script:
if tag.has_attr('src') and not any(x in tag['src'] for x in ['static', 'https','http']):
src = tag['src']
static_src = "{% static " + f"'{src}'" + " %}"
tag['src'] = static_src


for link in links:
if not any(x in link['href'] for x in ['static', 'https','http']):
href = link['href']
static_href = "{% static " + f"'{href}'" + " %}"
link['href'] = static_href
if img:
for image in img:
if not any(x in image['src'] for x in ['static', 'https','http']):
img_src = image['src']

static_img = "{% static " + f"'{img_src}'" + " %}"
image["src"] = static_img



for image in img:
if not any(x in image['src'] for x in ['static', 'https','http']):
img_src = image['src']

static_img = "{% static " + f"'{img_src}'" + " %}"
image["src"] = static_img

if bool(custom_tag) and bool(custom_attr):
for element in custom:
if element.has_attr(custom_attr) and not any(x in element[custom_attr] for x in ['static', 'https','http']):
attr_val = element[custom_attr]
jinja_value = "{% static " + f"'{attr_val}'" + " %}"
element[custom_attr] = jinja_value




# edit the html to add if statements to the elements with if attribute
for element in elements_with_if:
val = element['if']
if val:
possible_else = element.find_next_sibling()
if_val = "{% if " + f"{val}" + " %}"
element.insert_before(if_val)

while possible_else.has_attr('elif') or possible_else.has_attr('else'):
if possible_else.has_attr('elif') and possible_else['elif'] != '':
possible_else.insert_before("{% elif " + f"{possible_else['elif']}" + " %}")
del possible_else['elif']
elif possible_else.has_attr('else'):
possible_else.insert_before("{% else %}")
del possible_else['else']

possible_else = possible_else.find_next_sibling()

possible_else.insert_before("{% endif %}")
del element['if']


for element in elements_with_for:
val = element['for']
if val != '':
for_val = "{% for " + f"{val}" + " %}"
element.insert_before(for_val)

element.insert_after("{% endfor %}")
del element['for']


if edit_form:
forms = soup.find_all('form')
for form in forms:
if "{% csrf_token %}" not in form.getText():
form.insert(0, "{% csrf_token %}")

if edit_a:
aElms = soup.find_all('a')
for a in aElms:
if a.has_attr('href') and not any(x in a['href'] for x in ['static', 'https','http']) and not a['href'].startswith('#') \
and not a['href'].startswith('mailto') and not a['href'].startswith('{% url'):
href = a['href']
if href.startswith('/'):
href = href[1:]
if href.endswith('/'):
href = href[:-1]
if href.endswith('.html'):
href = href[:-5]
if href.endswith('.htm'):
href = href[:-4]
static_href = "{% url " + f"'{href}'" + " %}"
a['href'] = static_href


# Prettifying the output with beautiful soup prettify() method
modified_html = soup.prettify(formatter='html')

with open(file, 'w') as f:
f.write(modified_html)



if __name__ =="__main__":
djangoify('index.html')