使用 jinja2 模板指令加载外部脚本 [英] Loading external script with jinja2 template directive

查看:36
本文介绍了使用 jinja2 模板指令加载外部脚本的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对 jinja2 和一般模板的使用非常陌生,所以我想知道是否有一种简单的方法来加载外部 javascript.我正在考虑使用:

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 %}

但我忍不住要问:

有没有办法直接从模板指令中加载这个脚本?

推荐答案

这里你有两个选择——第一个是你做的方式——只需将适当的标记添加到模板(或者如果你想添加一个块)能够在扩展您的第一个模板的模板中覆盖它.)

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

第二种方式是使用Jinja2的include 功能:

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 %}

使用 include 的优点是 Jinja2 会在包含之前处理您的 javascript —— 这意味着您可以在您的 javascript 中拥有根据程序状态而变化的变量.

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.

以这种方式使用 include 的缺点是一样的——你的 .js 文件在发送之前会通过 Jinja2 运行——如果你不使用动态内容,您只会为每个请求不必要地处理文件——如果您使用的是具有 Jinja2 语法的 javascript 模板库,则可能会出现问题.

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.

这篇关于使用 jinja2 模板指令加载外部脚本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆