gpt4 book ai didi

python - 当模板具有内联 JS 时缩小 Flask 应用程序?

转载 作者:太空宇宙 更新时间:2023-11-03 15:06:08 25 4
gpt4 key购买 nike

部署应用程序之前的常规惯例是缩小所有 Assets (css、html、js)。这通常假设所有 Assets 都在一个独立的文件中(即,所有 js 代码都在 /js/mycode.js 中,这使得缩小 Assets 更容易。

但是,我写了一堆具有 <script> 的 jinja2 模板。它们中的标签,并且它们使用模板的变量。这对于快速编写 UI 很有用,但我想知道将所有这些迁移到一个 js 文件中以便我以后可以进行缩小的最佳方法是什么?

例如,我有很多具有内联 js 的模板:

<div class="some_content">
<button>{{mytext}}</button>
</div>
<script>
$(".some_content button").click(function() {
$(this).text("{{new_text}}");
$.post("{{url_for('doit', name=name)}}", function() {
console.log('Done!');
});
});
</script>

我知道我可以将 js 代码填充到一个文件中,然后执行 {% include 'mycode.js' %} ,但随后我会将我所有的 js 代码导入到模板中。一些模板具有继承性,因此执行 include 语句将导致文件将整个脚本多次加载到页面中(不好)。而且我不确定包含这样的脚本如何与缩小一起使用。

有没有一种好的方法可以将所有内联 JS 代码移动到外部文件,同时又不失去 jinja2 模板变量的好处,这样我就可以缩小我的 javascript?或者更确切地说,什么是缩小我所有内联 JS 的好方法?

最佳答案

您可以为此使用 jinja-assets-compressor。

https://github.com/jaysonsantos/jinja-assets-compressor

app.py

from jac.contrib.flask import JAC
from flask import Flask, render_template
import jinja2
from jac import CompressorExtension

app = Flask(__name__)
app.config['COMPRESSOR_DEBUG'] = app.config.get('DEBUG')
app.config['COMPRESSOR_OUTPUT_DIR'] = './static'
app.config['COMPRESSOR_STATIC_PREFIX'] = '/static'
jac = JAC(app)

env = jinja2.Environment(extensions=[CompressorExtension])
env.compressor_output_dir = './static'
env.compressor_static_prefix = '/static'
env.compressor_source_dirs = './static_files'


@app.route("/")
def hello():
return render_template('index.html', name='rublex')

if __name__ == "__main__":
app.run()

index.html

<!doctype html>
<html class="no-js" lang="">
<head>
<meta charset="utf-8">
<meta http-equiv="x-ua-compatible" content="ie=edge">
<title>Flask test</title>
</head>
<body>
<h1>Hello World</h1>
<button onclick="sayHi()">Say Hi</button>

{% compress 'js' %}
<script>
function sayHi() {
alert('{{ name }}');
}
</script>
{% endcompress %}
</body>
</html>

输出 JS

<script type="text/javascript" src="/static/62280e86f267fdbbd0cd10bb7b5ae3dc.js"></script>

function sayHi(){alert('rublex');}

关于python - 当模板具有内联 JS 时缩小 Flask 应用程序?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32418637/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com