在导入前端模板时,总是要手工处理所有引用,这里写一份代码,解决这个问题:
import re
def change_static(script_origin: str):
script_origin = script_origin.split('\n')
for script_origin in script_origin:
script_origin = script_origin.strip()
if script_origin:
check_index = [substr.start() for substr in re.finditer('\"', script_origin)]
start_index = check_index[0]
end_index = check_index[1]
script_str = script_origin[start_index + 1:end_index]
version_info = script_str.find('v=')
if version_info > 0:
script = script_str[:version_info - 1]
else:
script = script_str
script_origin = script_origin.replace(script_str, "{% static \'" + script + "\' %}")
print(script_origin)
if __name__ == '__main__':
script = '''
<script src="js/jquery.min.js?v=2.1.4"></script>
<script src="js/bootstrap.min.js?v=3.3.6"></script>
<script src="js/plugins/flot/jquery.flot.js"></script>
<script src="js/plugins/flot/jquery.flot.tooltip.min.js"></script>
<script src="js/plugins/flot/jquery.flot.spline.js"></script>
'''
change_static(script)
会打印:
<script src="{% static 'js/jquery.min.js' %}"></script>
<script src="{% static 'js/bootstrap.min.js' %}"></script>
<script src="{% static 'js/plugins/flot/jquery.flot.js' %}"></script>
<script src="{% static 'js/plugins/flot/jquery.flot.tooltip.min.js' %}"></script>
<script src="{% static 'js/plugins/flot/jquery.flot.spline.js' %}"></script>