Loading external script with jinja2 template directive

孤街浪徒 提交于 2019-11-28 17:17:06
Sean Vieira

You have two choices here -- the first is the way you did it -- simply add the appropriate markup into a template (or a block if you want to be able to override it in templates which extend your first template.)

The second way is to use Jinja2's include function:

{% block javascript %}
    <script type="text/javascript">
        {% include "myscript.js" %}
    </script>
    <!-- The contents of myscript.js will be loaded inside the script tag -->
{% endblock %}

The advantage of using include is that Jinja2 will process your javascript before including it -- which means you can have variables in your javascript that change depending on the state of your program.

The disadvantage of using include in this manner is the same -- your .js file will be run through Jinja2 before being sent out -- if you are not using dynamic content you will just be processing the file unnecessarily for every request -- and if you are using a javascript templating library with Jinja2 syntax then trouble is likely.

This question is quite old, but there is another way of doing it that might be interesting as well. I found it while working with Jinja2 and flask.

I used the url_for() and it works fine:

{% block javascript %}
    <script src="{{ url_for('static',filename='myscript.js') }}"></script>
{% endblock %}

And I have my myscript.js in my static folder. Specified in Jinja2 environment, or by default in flask.

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