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?
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.
There exists a python package which does that for you, please refer to : https://pypi.org/project/djangify/
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With