问题
I'm developing a template that will be included into a larger template, and for some reason the template is not accepting any arguments in Javascript.
Everything is fine if the argument is accessed from the html. Here's an example:
test.tpl:
<p>from html: {{arg}}</p>
<script type="text/javascript">
window.alert("from script "+{{arg}});
</script>
From another template, I include test.tpl and pass it with a arg value:
main.tpl:
% include('test.tpl', arg='some value')
The end result is that, the argument in html is displayed fine:
from html: some value
But the windows alert gives something weird:
[object HTMLLIElement]
What is going on?
回答1:
As @dandavis pointed out in the comment, the proper way to reference the argument in javascript is to put it in a quote:
test.tpl:
<p>from html: {{arg}}</p>
<script type="text/javascript">
window.alert("from script "+"{{arg}}");
</script>
Output:
from script some value
Without the quotation mark, what JavaScript actually sees is a string followed by a variable called some value, which is not cannot be concatenated with a string literal. This is how my original code looks like to the browser:
window.alert("from script " + some value);
which is wrong.
来源:https://stackoverflow.com/questions/29501534/bottlepy-how-to-access-bottle-arguments-var-from-javascript