【问题标题】:Use Jinja2 template engine in external javascript file在外部 javascript 文件中使用 Jinja2 模板引擎
【发布时间】:2014-03-24 06:29:18
【问题描述】:

我正在使用 Python 和 Flask 开发一个 Web 项目。我只是想知道我是否可以在我的外部 javascript 文件中访问 python 发送的参数?它适用于 html 文件或嵌入在 html 文件中的 js,但当 javascript 为外部时则不行。

见下文。

python 代码

@app.route('/index')
def index():
    return render_template('index.html', firstArg = 2, secondArg = 3)

index.html 代码

...
<body>
    <p>The first arg is {{firstArg}}.</p>
    <script src="index.js"></script>
</body>
...

还有 index.js 文件

window.onload=function(){
    console.log('{{secondArg}}');
};

所以第一个参数在 html 文件中是正确的,但第二个在 js 文件中不起作用。浏览器显示Unexpected token {

可能在外部js中无法使用?

否则我需要在 html 中插入 secondArg 作为输入数据并在 js 文件中获取它,但它不是很干净。

如果有人可以帮忙,谢谢。

【问题讨论】:

    标签: javascript python flask external jinja2


    【解决方案1】:

    此外,您可以在需要的地方创建 index_js.html(或相同的 index.js)文件和 {% include 'index_js.html' %}

    1) 如果你喜欢index_js.html - 使用&lt;script&gt; here is some JS templated code &lt;/script&gt; 那里。进一步:{% include 'index_js.html' %} 在您的模板化 html 中。

    2) 或者,如果您喜欢 index.js - 请使用 &lt;script&gt; {% include 'index.js' %} &lt;/script&gt;

    【讨论】:

      【解决方案2】:

      您的烧瓶实例可能不提供 index.js,但它肯定不会由您的模板引擎处理,即使它不会与请求的 html 具有相同的上下文。

      我认为最干净的解决方案是在您的 index.js 中添加一个启动函数并从 html 文件中调用它:

      <body>
          <p>The first arg is {{firstArg}}.</p>
          <script type="text/javascript" src="index.js"></script>
          <script type="text/javascript">
              yourInitFunction({{secondArg}});
          </script>
      </body>
      

      您也可以告诉 flask 路由 index.js:@yourapp.route('index.js'),就像您对 route('/index') 所做的那样,但这可能不是一个好主意。

      【讨论】:

      • 谢谢。我将通过从 HTML 调用函数来采用您的解决方案。我只是有一个问题,路由 index.js 会有什么影响?我不明白你的意思,我以为只是路由,我看不到js文件的链接。
      • 当您添加路由时,flask 将通过调用修饰函数(即app.route() 之后的函数)来处理路由参数的 GET 请求。因此,您可以捕获对“index.js”的所有请求,进行一些计算并让模板引擎像您的 html 文件一样呈现 javascript 文件。 PS:如果你觉得我的回答对你有帮助,我会很感激你接受它。
      • 哇。是的,为什么在可以像这样注入时将 js 文件渲染为模板。很优雅。很干净。惊奇谢谢。它还强制执行某种架构方式,不在 js 文件中硬编码内容。
      猜你喜欢
      • 2018-05-04
      • 2011-04-10
      • 1970-01-01
      • 2016-08-23
      • 2018-07-15
      • 2015-08-22
      • 1970-01-01
      • 2023-03-21
      • 1970-01-01
      相关资源
      最近更新 更多