简体   繁体   English

Javascript无法在Flask jinja2模板中正确呈现

[英]Javascript not rendering correctly in Flask jinja2 templates

I'm writing a Flask app using jinja2, and I'm trying to pass my Python variables both into some Javascript and HTML. 我正在使用jinja2编写Flask应用,并且试图将我的Python变量都传递给某些Javascript和HTML。 I made Javascript and HTML templates, but for some reason the Javascript is getting rendered and displayed in the wrong place, and I can't figure out what the problem is. 我制作了Javascript和HTML模板,但是由于某种原因Java语言被渲染并显示在错误的位置,因此我无法弄清楚问题出在哪里。

My controller code that passes my Python data, and renders my templates is: 传递我的Python数据并呈现我的模板的控制器代码是:

@info_page.route('/info.html', methods=['GET'])

def info():
    ''' Documentation here. '''

    session = db.Session()
    infoDict = {}
    jsDict = {}

    ... 

    infoDict['character'] = character
    infoDict['name']=name
    jsDict['powertree']=powertree

    js = render_template('powertree.js', **jsDict)
    infoDict['js']=js

    return render_template("info.html", **infoDict)

The template for info.html is: info.html的模板为:

{% extends "layout.html" %}

{% block head %}
    <link rel="stylesheet" type="text/css" href="    {{url_for('static',filename='css/index.css')}}">
{% endblock head %}

{% block code %}
   {{js}}
{% endblock code %}

{% block body %}
    <h1>{{name}}</h1>
  ...
{% endblock body %}

And the template for powertree.js is: 而且powertree.js的模板是:

 <script type='text/javascript'>
    $(document).ready(function() {

    var data = {{powertree}};
    console.log('hello, inside powertree');

    });
 </script>

The rendered Javascript code is just visibly printed at the top of my webpage. 呈现的Javascript代码仅显示在我的网页顶部。 Looking at the DOM shows it's displayed inside the HTML body and not inside the HTML head, where it belongs. 查看DOM会发现它显示在HTML主体内,而不是显示在它所属的HTML头内。 If I remove the {{js}} and replace it with the actual code inside powertree.js , everything renders fine, and works as expected. 如果删除{{js}}并将其替换为powertree.js的实际代码,则所有内容都会正常显示,并且可以正常工作。 However I'd rather keep my Javascript in a separate file as it will get quite long. 但是,我宁愿将Javascript放在单独的文件中,因为它会变得很长。 Why doesn't this work? 为什么不起作用? How can I easily pass my variables into Javascript code so I can reference, in this example {{powertree}} in my js? 我如何轻松地将变量传递到Javascript代码中,以便在js中的本示例{{powertree}}中进行引用? Because it just visibly prints the Javascript at the top of my webpage, it makes me think it's a simple syntax error with a missing or something like that, but I can't find anything. 因为它只是在页面顶部明显地显示Javascript,所以让我认为这是一个简单的语法错误,缺少内容或类似内容,但是我什么也找不到。

Thanks. 谢谢。

What happened is that for all files with filename extension .html (and a few others ) certain safeties are applied, namely the filtering out of html special characters (like < , > and a few others, refer to the documentation ) by converting them to the html entities equivalent. 发生的事情是,对于文件扩展名为.html所有文件(以及其他一些文件 ),都应用了某些安全措施,即通过将html特殊字符(例如<>和其他一些文件请参见文档 )转换为HTML特殊字符进行过滤等效的html实体。 To ensure that the strings are not escaped, you want to change the rendering part to: 为了确保不对字符串进行转义,您想将渲染部分更改为:

{% block code %}
   {{js|safe}}
{% endblock code %}

Note that you have to be sure that your code will not contain any raw user input, as that opens up XSS vulnerability. 请注意,您必须确保您的代码不会包含任何原始用户输入,因为这会打开XSS漏洞。

Another solution is to mark the js variable as being safe for inclusion directly in your python code by using the Markup class: 另一个解决方案是使用Markup类将js变量标记为可以安全地直接包含在python代码中:

from jinja2 import Markup

infoDict['js']= Markup(js)

This is preferable to using the |safe filter in the template code because: 这比在模板代码中使用|safe过滤器更可取,因为:

  1. you can indicate that a variable is safe at the place where it is defined; 您可以指示变量在定义的位置是安全的; this avoids having to remember this information and can possibly prevent double escaping. 这避免了必须记住此信息,并可能防止了两次转义。
  2. in the case where templates and Python code are written separately (eg by two different people, or at different times), you don't need to communicate the safeness of variables to the template designer. 如果模板和Python代码是分开编写的(例如,由两个不同的人或在不同的时间编写),则无需向模板设计者传达变量的安全性。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM