Converting HTML to Django Template

I want to create a python script that will modify 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 shouldn't think worth posting 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 many static assets referenced in the usual 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 was trying to create a script that looks for "assets" and edits the line, replaces href="assets

with href="{% static'

... and then appends ' %}

to the end. I think this would be a very valuable script for django developers who work with templates, maybe it's already out there somewhere.

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

+3


source to share


1 answer


I am assuming you know regular expressions. My preferred way to make such a change is to use a regular expression enabled editor, then it's a matter of find and replace. If you're using Django, jetbrains' pycharm is well worth the money. I like vim.

Each editor has several options for how regex capture groups work (please check your editor / ide docs), but the general format for such a regex is:

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

      



It searches for an attribute src

or href

, starting with assets

, capturing everything between the quotes. Thus, capture group 1 is an attribute, and capture group 2 is a value - a replace expression:

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

      

In some editors, you must use $1

and $2

instead of \1

and \2

. In vim, you should avoid Parens IICR. Also, some editors do not support this ( .+?

) syntax for non-greedy "grabbing everything" you might need to use [^"]+

.

+4


source







All Articles