0

我对 jinja2 比较陌生(而且绝不是网络开发专家),我无法根据程序状态的变化让与 jinja 模板关联的 javascript 重新加载(并更新其变量)。

本质上,我有一个模板遍历项目列表:

{% for item in items %}
<p> {{item['property a']}}</p>
blah blah blah`

然后我调用我在该 for 循环中导入的另一个模板:

{% import 'secondTemplate.html' as s %} //not sure whether this matters if it goes inside or outside the for loop
<p> {{s.doSecondStuff(item)}}</p>

这一切都有效。第二个模板每次执行每个项目,这是我想要的。

但是,我有一些与 secondTemplate.html 关联的 secondTemplate.js,它对传递给 secondTemplate.html 的变量进行操作。我的问题是 secondTemplate.js 只对第一项的值进行操作。

使用 jinja2 模板指令加载外部脚本的最佳答案似乎是可行的,所以我一直在尝试将以下内容放入 for 循环中:

{% block javascript %}
    <script type="text/javascript">
        {% include "secondTemplate.js" %}
    </script>
{% endblock %}

但是 js 仍然只反映列表中第一项的值。

有任何想法吗?谢谢!

4

2 回答 2

2

If you open your Flask app with a browser, Flask looks through the routes you defined and selects the one that it finds the most appropriate, for example:

@app.route('/<name>')
def index(name):
    return render_template('index.htm', var1=name)

It executes the inside of the function like a normal function in any programming language. And here is the point: The function only returns a string of HTML. It doesn't do any "magic" to pass any information about variable names to the browser. To be concrete, if index.htm looked like this:

<h1>Hello {{ name }}!</h1>

Then render_template('index.htm', name="world") returns a string with the content "<h1>hello world!</h1>", which is what your view returns, which is what Flask gives the browser.

So the browser, and therefore your Javascript code, have absolutely no idea which part of the HTML was a variable and which not. By the time you are executing Javascript in the browser, your Flask app already has forgotten about the client and the value of name it was given.

It's really unclear what you are asking, but i hope i made it clear to you how the thing you are trying to achieve will not be possible in that way.

于 2013-07-27T15:53:39.350 回答
1

我不熟悉 jinja,但是如果你想重新加载 js 文件(如果我理解你的话),有一个像下面这样的技巧。让我们用 id 制作所有标签,所以:

<script src="be/happy.js" id ="be/happy.js"></script>
<script src="be/very/happy.js" id ="be/very/happy.js"></script>

等等。现在是线索。我们可以使用以下方法强制浏览器再次加载文件:

var s = document.getElementById('be/happy.js'); //get access to node
d.parentNode.removeChild(s); //remove it from document
delete d; //destroy element

d = document.createElement('script'); //create new script tag
d.src = d.id = 'be/happy.js'; //add the same value to id and src attribute
document.getElementsByTagName('head')[0].appendChild(d); //append child again, what force browser to script reload
于 2013-07-26T23:32:26.023 回答