django replace html href and src to a {% static %} tag
Asked Answered
H

2

5

how I can django replace html href and src to a static tag in Pycharm? For example:

<link rel="stylesheet" href="libs/owlcarousel/assets/owl.carousel.min.css">
<a href="/"><img src="img/logo.png" alt=""></a>

into

<link rel="stylesheet" href="{% static 'landing/libs/owlcarousel/assets/owl.carousel.min.css' %}">
<a href="/"><img src="{% static "landing/img/logo.png" %}" alt=""></a>

thx!

Hindquarter answered 22/7, 2018 at 18:56 Comment(0)
C
8

You can find and replace into the project with Ctrl + Shift + R.

Into the file selection, you can specify that you want to perform replacements in *.html files, and that we want to search for a regex (check the checkbox Regular expression).

As pattern, you can write a pattern like:

\b(src|href)="([^"]*)"\b

and as patttern to replace:

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

You might want to consider tweaking the pattern a bit, for example to only replace paths that start with libs/, etc.

this will then propose the changes. I advise you to look through these manually since there can be false positives: proposed changes, that should not change.

Concede answered 22/7, 2018 at 19:4 Comment(2)
This pattern doesn't work for me in Pycharm 2020.1 Can you suggest an adjustment Willem? Would be a big helpBandit
Can you suggest a LINUX sed command for this?Pneumothorax
S
1

Above answer didn't help me, so I created my own.

find: <(link|img|script)[^>]*(?:href|src)=["']([^"']*)["']

replace: <$1 src="{% static '$2' %}"

Selfsacrifice answered 24/10, 2023 at 15:51 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.