Created
September 19, 2018 14:47
-
-
Save aruseni/70f5984f7e0e4d3e216d96d4455a6ff3 to your computer and use it in GitHub Desktop.
A Python script that replaces all text nodes inside a `template` element with [TXT], used with Vue templates
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import argparse | |
parser = argparse.ArgumentParser(description='Replace text nodes') | |
parser.add_argument('file', type=str) | |
args = parser.parse_args() | |
html = open(args.file).read() | |
def replace(content): | |
updated_content = '' | |
if content[0] == ' ': | |
updated_content += ' ' | |
updated_content += '[TXT]' | |
if content[-1] == ' ': | |
updated_content += ' ' | |
return updated_content | |
def update_html(html): | |
updated_html = '' | |
collecting = False | |
content = '' | |
for char in html: | |
if char == '<': | |
collecting = False | |
if content: | |
if content.strip(): | |
updated_html += replace(content) | |
else: | |
updated_html += content | |
content = '' | |
updated_html += char | |
elif char == '>': | |
collecting = True | |
updated_html += char | |
else: | |
if collecting: | |
content += char | |
else: | |
updated_html += char | |
return updated_html | |
html_lines = html.split('\n') | |
for i, line in enumerate(html_lines): | |
if line == '<template>': | |
first_template_line = i | |
elif line == '</template>': | |
last_template_line = i | |
pre_template_code = '\n'.join( | |
html_lines[:first_template_line] | |
) | |
template_code = '\n'.join( | |
html_lines[first_template_line:last_template_line+1] | |
) | |
post_template_code = '\n'.join( | |
html_lines[last_template_line+1:] | |
) | |
parts = [] | |
# So we don’t add an unnecessary blank line in the beginning of the file | |
if pre_template_code: | |
parts.append(pre_template_code) | |
parts.append(update_html(template_code)) | |
parts.append(post_template_code) | |
print('\n'.join(parts)) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment