在Django模板中执行Javascript和CSS [英] Execute Javascript and css in Django template
问题描述
我正在通过Django应用中的Weasyprint将HTML导出为PDF.我注意到,如果我将模板html发送到前端,并将该html返回到后端以将其导出为pdf,则可以完美打印.但是,如果我直接将模板html发送到Weasyprint,则会搞砸一切!没有CSS,没有JavaScript.
I am exporting HTML to PDF via Weasyprint in my Django app. I have noticed that if I send the template html to front end and return that html to backend to export it to pdf, it prints perfectly. But if I directly send template html to Weasyprint, it messes up everything! No css, no javascript.
这就是我使用模板生成html的方式:
This is how I'm using the template to generate html:
template = loader.get_template('Reporting/reportTemplate.html')
context = {
"reportObj" : result[0]
}
htmlContent = (template.render(context, request))
response['message'] = htmlContent
return JsonResponse(response)
在我的JS控制器中,我将htmlContent分配给div:
In my JS controller I assign the htmlContent to my div:
$('#htmlContent').html(response.message);
然后我将生成的html返回我的Django函数以打印pdf
Then I return the generated html back to my Django function to print pdf
HTML(string=htmlContent).write_pdf(target=response, stylesheets=[CSS(string=getCSS())])
通过这种方式可以维护设计和所有内容.
This way it maintains the design and everything.
但是当我直接将 htmlContent
发送到Weayprint而没有将其发送到前端时,设计和着色就消失了!
But when I send htmlContent
directly to Weayprint without sending it to front end, the design and coloring is gone!
在我的模板中,我什至包括了CSS和Javascript文件,如下所示:
In my template, I even have included CSS and Javascript files like this:
{% load static %}
{% block content %}
<link href="{% static "css/ion.rangeSlider.css" %}" rel="stylesheet">
<link href="{% static "css/ion.rangeSlider.skinHTML5.css" %}" rel="stylesheet">
<script type='text/javascript' src='{% static "scripts/ion.rangeSlider.js" %}'></script>
<script type='text/javascript'>
$(document).ready(function(){
var creditScore = $("#creditScore").html();
$("#rangeCS").ionRangeSlider({
type: "double",
min: 0,
max: 1000,
step: 100,
from: 0,
to: creditScore,
from_fixed: true,
to_fixed: true,
grid: true,
grid_snap: true
});
});
</script>
{% endblock %}
如何在Django模板中执行Javascript和CSS并将其导出为PDF,而不必将其发送到前端?
推荐答案
就像mille_a所说,您无法将javascript代码转换为pdf.
Like mille_a said, you can't execute javascript code into a pdf.
因此,要解决您的问题,您需要在视图中进行操作:
So to resolve your problem you need to do it into your view :
# do some python stuff to get somes datas
datas = ...
# assign it into your html
htmlContent = my_html_template.render(datas)
# call the pdf generation
HTML(string=htmlContent).write_pdf(target=response)
You can see this example for more details : http://www.supinfo.com/articles/single/379-generate-pdf-files-out-of-html-templates-with-django
希望有帮助.
这篇关于在Django模板中执行Javascript和CSS的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!