Use Jinja2 template engine in external javascript file

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>.


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.