简体   繁体   中英

Convert HTML to Django template

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.

有一个 python 包可以为你做这件事,请参考: https : //pypi.org/project/djangify/

This is the command for vi editor. Run this in escape mode.

:%s/href="([^ ]+)"/href="{% static \1 %}"/g

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM