Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert HTML to Django template

Tags:

python

html

I want to create a python script that would change html documents, I'm kind of lost and don't know where to start, I've tried a couple of things that didn't work at all and don't think its worth posting them here.

The problem is that with Django, it is better to write links like this:

    <link href="{% static 'assets/css/cssfile.css' %}"/>
    <script src="{% static 'assets/js/jsfile.js' %}"></script>
    <img src="{% static 'assets/images/desktop.png' %}"/>

But I have a template, actually several templates, with lots of static assets that are referenced in the normal way, like this:

<link href="assets/css/cssfile.css" rel="stylesheet"/>
<script src="assets/js/jsfile.js"></script>
<img src="assets/images/desktop.png"/>

So, I've been trying to create a script that looks for "assets" and the edits the line, replacing href="assets with href="{% static'... and then adds ' %} at the end. I think this would be a very valuable script for django developers that work with templates, maybe it is already out there somewhere.

Is there any automated way to convert the normal href/src attributes to use Django tags?

like image 620
Alejandro Veintimilla Avatar asked May 15 '26 04:05

Alejandro Veintimilla


2 Answers

I assume you know regular expressions. My prefered way to make this kind change is using an editor with regular expression support, then it is a matter of search & replace. If you are using Django, pycharm from jetbrains is well worth the money. I like vim.

Each editor has some variation on how regex capture groups work (please, check your editor/ide docs), but the general format of such a regular expression is:

(src|href)="(assets\/.+?)"

It is searching for a src or href attribute starting with assets, capturing everything between the quotes. So, capture group 1 is the attribute and capture group 2 is the value - the replace expression is:

\1="{% static '\2' %}"

On some editors you must use $1 and $2 instead of \1 and \2. In vim you must escape the parens IICR. Also, some editors do not support this syntax (.+?) for non-greedy "capture everything", you may have to use [^"]+ instead.

like image 64
Paulo Scardine Avatar answered May 17 '26 16:05

Paulo Scardine


There exists a python package which does that for you, please refer to : https://pypi.org/project/djangify/

like image 23
Amartya Gaur Avatar answered May 17 '26 17:05

Amartya Gaur



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!