How to structure dynamic javascript creation in Flask?

I am building a website using a (excellent) Python flash framework that has a folder templates/

and a static/

folder in it. As the name suggests, the templates folder contains templates that are rendered through the jinja2 templating engine , while the static folder contains static content such as css, images, and static javascript files.

The javascript files are what I ran into. Sometimes I want to place a jinja variable in a js chunk, like for example:

var requestJson = {'text': messageText, 'toUserId': {{ user.id }}};

      

If I do it in a file .js

in a folder static/

but it doesn't show up, so it only works if I put it between tags <script>

in the template file. This works, but it seems useless because now I have some js in the static folder and some js in my template files.

I could of course solve this by specifying document.toUserId = {{ user.id }};

in the template and using that in the .js files, but yes, that also looks like a hack.

So my question is; what is the best / pythonic / simplest way to handle inserting dynamic values ​​from jinja into javascript?

+3


source to share


1 answer


A very interesting question that I thought about a lot at a certain point in time. So far I have done it and seen how it is done this way, and it seems to me that this is the best and most pythonic option. I think I can remember it even from the Flask documentation (can't remember where).

Just supply specific variables that need the template to be rendered in script in your files .html

using the appropriate namespaces.

And everything else in your files .js

(I happen to be using CoffeeScript, so it's even more important for me to use minimal code in tags <script>

directly in the template, for consistency reasons).



For example, here's a (slightly modified) script that's at the end of the template I'm currently working with:

<script>
  $(function() {
    window.my_namespace.view_dashboard_vars = {};
    window.my_namespace.view_dashboard_vars.change_widgets_positions_url = "{{ url_for('dashboard.change_widgets_order', _external=True) }}";
    window.my_namespace.view_dashboard_vars.deactivate_widget_url = "{{ url_for('dashboard.deactivate_widget', _external=True) }}";
    window.my_namespace.view_dashboard_vars.dashboard_url = "{{ url_for('dashboard.view_dashboard', dashboard_id=dashboard.id, _external=True) }}";
    window.my_namespace.view_dashboard_vars.dashboard_id = "{{ dashboard.id }}";
    $(document).ready(function() {
        $("select#dashboard_dates_presets").val("{{ preset }}");
        my_namespace.update_dashboard_dates_interval();
    });
  });
</script>

      

It works very well, and after several projects, and some of them are already quite a lot around, with a lot of people, I can say that it is perfectly readable and supported. Just be careful to choose the right namespaces.

+3


source







All Articles