2015-09-05 41 views
3

部署应用程序之前的常规约定是缩小所有资产(css,html,js)。这通常假设所有的资产都在一个独立的文件(即所有的JS代码是在/js/mycode.js,这使得涅槃资产更容易。当模板具有内联JS时最小化Flask应用程序?

不过,我已经写了一堆有<script>标签他们Jinja2的模板,并且他们使用了模板的变量,这对于快速编写用户界面非常有用,但是我想知道将所有这些迁移到一个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> 

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

有没有一种很好的方式将所有内联JS代码移动到外部文件,而不会失去jinja2的模板变量的好处,以便我可以缩小我的JavaScript?或者说,什么是缩小所有内联JS的好方法?

+1

我只是不打扰。将模板中的动态JS留在模板中,直到证明存在实际的带宽问题(除非您是堆栈溢出的大小,否则不会有此问题)。 – davidism

回答

4

您可以使用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');} 
相关问题