无法通过模板瓶将数据发送到 Javascript
Unable to Send Data to Javascript via Templates Bottle
我有一个小的 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。
>>> 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
的定义没有在 <script>
标签中引用。固定版本:
<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>
我有一个小的 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。
>>> 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
的定义没有在 <script>
标签中引用。固定版本:
<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>