【问题标题】:Unable to Send Data to Javascript via Templates Bottle无法通过模板瓶将数据发送到 Javascript
【发布时间】:2017-09-10 17:00:38
【问题描述】:

我有一个小的 Python 脚本,它应该向我的 HTML 文件中的 javascript 发送一个字符串,以便在页面上呈现。但是,该脚本没有接收从 Python 文件发送给它的数据。我的代码如下:

simple.html:

<html>
 <body>
   <h1>Hello</h1>
   <p1 id="demo"></p1>
   <script>
    var s  = {{to_display}};
    var x = document.getElementById("demo");
    x.innerHTML = s;
   </script>
 </body>
</html>

main.py:

from bottle import Bottle, template

app = Bottle()

@app.route('/')
def index():
   data = {"to_display":"HI, how are you"}
   return template("simple.html", data)

if __name__ == '__main__':
    app.run()

我希望页面看起来像这样:

Hello

HI, how are you

不幸的是,它只显示:

Hello

有人知道如何解决这个问题吗?

【问题讨论】:

    标签: javascript python html jinja2 bottle


    【解决方案1】:

    这里的问题是模板没有呈现有效的javascript。

    >>> from bottle import template
    >>> data = {'to_display': 'HI, how are you'}
    >>> rendered = template('/home/kev/tmp/test.html', data)
    >>> print rendered
    <html>
      <body>
        <p1 id="demo"></p1>
        <script>
            var s = HI, how are you;
            var x = document.getElementById("demo");
            x.innerHTML = s;
        </script>
      </body>
    </html>
    

    在浏览器中加载此 html 会引发语法错误(在 Firefox 52.3.0 上测试):

    SyntaxError: missing ; before statement

    问题是s 的定义没有在&lt;script&gt; 标记中引用。固定版本:

    <html>
      <body>
        <p1 id="demo"></p1>
        <script>
            var s = "{{ to_display }}";
            var x = document.getElementById("demo");
            x.innerHTML = s;
        </script>
      </body>
    </html>
    

    渲染到这个标记,它在浏览器中按预期工作:

    >>> print rendered
    <html>
      <body>
        <p1 id="demo"></p1>
        <script>
            var s = "HI, how are you";
            var x = document.getElementById("demo");
            x.innerHTML = s;
        </script>
      </body>
    </html>
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2017-12-26
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-06-25
      • 1970-01-01
      • 2013-08-10
      • 1970-01-01
      相关资源
      最近更新 更多