Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
402 views
in Technique[技术] by (71.8m points)

python - Loading external script with jinja2 template directive

I'm very new to jinja2 and the use of templates in general so I was wondering if there's an easy way to load an external javascript. I was thinking of using:

{% block javascript %}
    <script src="myscript.js"></script>
{% endblock %}

But I can't help to ask:

Is there a way of loading this script directly from within a template directive?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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.


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

2.1m questions

2.1m answers

60 comments

57.0k users

...