在实际Django项目开发中,我们常会在Django后端views.py中调用其他算法,然后将算法返回的结果传输至前端展示,但有时可能会在后端返回一些html代码,例如对某些文字加粗、加颜色等,这时就需要使后端传输的数据为html代码。
通常使用Django的render方法传输数据的类型为字符串,传输至前端后也不能按照html的格式展示,可通过ajax返回数据,然后前端通过innerHtml实现,但比较麻烦。
from django.utils.safestring import mark_safe
实际应用中可通过上述代码,引入mark_safe函数,将对应的需要传输的字符串处理即可在前端展示相应的格式。例如:
test = test.replace('[31m',"<font color='red'><b>")
test = test.replace("[0m","</b></font>")
test = "<font size='5'>" + test + "</font>"
test = mark_safe(test)
然后通过render方法将数据传输至前端即可。
return render(request, 'FileMatch.html',{'test':test})