js脚本未在jinja2模板中加载

时间:2015-04-02 08:44:47

标签: javascript python flask jinja2

我有一种情况,用jinja2变量"/CreditHistory/10216"替换url字符串{{creditNumbers|safe}}会混淆javascript文件的加载。更具体地说,这是有效的;

{% block Scripter %}

<script type="text/javascript" src="./static/assets/js/crossfilter/crossfilter.js"></script>
<script type="text/javascript" src="./static/assets/js/d3/d3.js" charset="utf-8"></script>
<script type="text/javascript" src="./static/assets/js/dc.js/dc.js"></script>
<script type="text/javascript" src="./static/assets/js/queue/queue.js"></script>
<script src='./static/assets/js/graphsFordringer.js' type='text/javascript' charset="utf-8"></script>
<script type="text/javascript"> 

queue().defer(d3.json, "/CreditHistory/10216").await(makeGraphs);

</script>

{% endblock %} 

但是,这不是;

{% block Scripter %}

<script type="text/javascript" src="./static/assets/js/crossfilter/crossfilter.js"></script>
<script type="text/javascript" src="./static/assets/js/d3/d3.js" charset="utf-8"></script>
<script type="text/javascript" src="./static/assets/js/dc.js/dc.js"></script>
<script type="text/javascript" src="./static/assets/js/queue/queue.js"></script>
<script src='./static/assets/js/graphsFordringer.js' type='text/javascript' charset="utf-8"></script>
<script type="text/javascript"> 

queue().defer(d3.json, "{{creditNumbers|safe}}").await(makeGraphs);

</script>

{% endblock %} 

在Web浏览器中抛出的错误意味着没有加载任何javascript文件。其中之一是例如队列不是定义的函数。 同样显而易见的是,"{{creditNumbers|safe}}"变量确实加载到"/CreditHistory/10216"。因此,简而言之,变量加载似乎打破了javascript加载。并不是说我在文档中找到了类似问题的参考,所以可能不是正在发生的事情。

编辑:

现在看来,我误解了整个情况。看起来这是jinja2模板变量在作为根本原因的app.py文件中声明的方式。

失败的@app.route代码是;

@app.route('/KundeFordringer/<int:KundeNr>')
def fordringer(KundeNr):

    jsonSti = "/CreditHistory/"+str(KundeNr)
    return render_template("fordringer.html", creditNumbers=jsonSti)

但是,如果我将代码更改为以下代码,它可以正常工作;

@app.route('/KundeFordringer')
def fordringer():

    return render_template("fordringer.html", creditNumbers="/CreditHistory/10216")

如前所述,从Web浏览器查看源代码,可以看到在使用第一个"/CreditHistory/10216"声明时加载了@app.route。但显然,通过这种方式,有些东西可以用来做。

非常感谢任何帮助

1 个答案:

答案 0 :(得分:1)

加载javascript文件是相对于当前网址的。 基本上如果你正在浏览

http://mywebsite.com/KundeFordringer/456

然后浏览器将尝试加载这些文件:

http://mywebsite.com/KundeFordringer/456/static/assets/js/crossfilter/crossfilter.js
http://mywebsite.com/KundeFordringer/456/static/assets/js/d3/d3.js
http://mywebsite.com/KundeFordringer/456/static/assets/js/dc.js/dc.js
http://mywebsite.com/KundeFordringer/456/static/assets/js/queue/queue.js

你想要的可能是

http://mywebsite.com/static/assets/js/crossfilter/crossfilter.js
http://mywebsite.com/static/assets/js/d3/d3.js
http://mywebsite.com/static/assets/js/dc.js/dc.js
http://mywebsite.com/static/assets/js/queue/queue.js

使用脚本标记可能会出现问题:

<script type="text/javascript" src="./static/assets/js/dc.js/dc.js"></script>

需要重命名

<script type="text/javascript" src="/static/assets/js/dc.js/dc.js"></script>

static_url_path的问题。