Use Jinja2 template engine in external javascript file

≯℡__Kan透↙ 提交于 2019-12-02 18:12:47

The index.js is probably not served by your flask instance, but it is most definitely not processed by your templateing engine and even if it would it would not have the same context as the html it is requested for.

I think the cleanest solution would be to have an initiation function in your index.js and call it from the html file:

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

You also could tell flask to route the index.js, too: @yourapp.route('index.js') just like you did with the route('/index') however this is probably not a very good idea.

Also, you may create index_js.html (or same index.js) file and {% include 'index_js.html' %} where you need it.

1) If you like index_js.html - use <script> here is some JS templated code </script> there. Further: {% include 'index_js.html' %} in your templated html.

2) Or if you like index.js - do <script> {% include 'index.js' %} </script>.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!