Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Minifying a Flask application when templates have inline JS?

The normal convention before deploying an application is to minify all assets (css, html, js). This usually assumes that all the assets are in an independent file (ie, all js code is in /js/mycode.js, which makes minifying the assets easier.

However, I have written a bunch of jinja2 templates that have <script> tags in them, and they make use of the template's variables. This has been useful for quickly writing UI quickly, but I'm wondering what the best way of migrating all this into one js file so that I can do minification later?

For example, I have lots of templates that have inline 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>

I am aware that I can stuff the js code into a file and then do {% include 'mycode.js' %}, but then I'd be importing ALL of my js code into the template. Some templates have inheritance, so then doing the include statement will cause the file to load the entire scripts multiple times into the page (not good). And I'm not sure how including scripts like this would work with minification.

Is there a good way to move all the inline JS code to an external file, without losing the benefits of jinja2's template variables, so that I can minify my javascript? Or rather, what's a good way to minify all my inline JS?

like image 819
rublex Avatar asked Sep 05 '15 23:09

rublex


1 Answers

You can use jinja-assets-compressor for this.

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>

Outputs JS

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

function sayHi(){alert('rublex');}
like image 116
duffn Avatar answered Nov 14 '22 23:11

duffn