Render JavaScript Within Flask

Render JavaScript Within Flask

So a while ago I wanted to use some JavaScript to do some auto-filtering on a dropdown box I had in Flask. However, this wasn’t a static JavaScript file, I needed some dynamic-ness based on some other functionality and couldn’t just serve up a static JavaScript file. What I found was that there weren’t a lot of good examples for what I wanted to accomplish. Most of the examples you see are html files with JavaScript in the script tags. Which is cool, I just didn’t want to do it that way.

First, write up your JavaScript and stick it in with your templates. I had to use $.getJSON(), so the dynamic part of my JavaScript within Flask looked like below. Basically it is querying my database and grabbing applicable data based on a previous user selection. I’m doing the grabbing with Flask and the making with JavaScript. If that makes sense. And please pardon my lack of technical JavaScript terminology.

// your_javascript.js
$.getJSON("{{ url_for('main._get_stuff') }}", send, function(data) {
            data.forEach(function(item) {
                dropdown.foo.append(
                    $('<option>', {
                        value: item[0],
                        text: item[1]
                    })
                );
            });
            dropdown.foo.removeAttr('disabled');
        });

Then you’ll want to render your JavaScript where your routes live. Mine looks similar to this:

@main.route('/some_route_you_chose')
def render_that_javascript():
    return render_template('your_javascript.js')

In the template you want your JavaScript in, put the url_for your rendered JavaScript in your block for scripts:

{% block scripts %}
<script src="{{ url_for('main.some_route_you_chose') }}"></script>
{% endblock %}

There you go. Flask rendering JavaScript that needed some dynamic content. Hopefully if you were trying to figure this out yourself you found it helpful. More next time!

-Rachel