python - How to structure dynamic javascript creation in Flask? -


i'm building website using (excellent) python flask framework in there templates/ folder , static/ folder. names suggest, templates folder contains templates rendered through jinja2 templating engine , static folder contains static content such css, images, , static javascript files.

the javascript files i'm having trouble though. want place jinja variable in piece of js example:

var requestjson = {'text': messagetext, 'touserid': {{ user.id }}}; 

if in in .js file in static/ folder though, isn't rendered, works if place between <script> tags in template file. works, feels kinda messy because have js in static folder, , js in template files.

i of course solve defining document.touserid = {{ user.id }}; in template , using in .js files, yeah, feels kinda hack.

so question is; best/pythonic/neatest way of handling insertion of dynamic values jinja in javascript?

very interesting question i've thought lot @ point in time. i've done , have seen done precisely way , seems me best , pythonic option. think can recall it's recommended flask documentation (can't remember where).

just put specific variables need template rendering in script in .html files, using appropriate namespaces.

and rest in .js files (i happen using coffeescript it's more important me put least code possible in <script> tags directly in template, consistency reasons).

for instance, here (slightly modified) script lies @ end of template i'm 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 , after several projects , of them being around quite bit now, lots of people involved, can tell it's readable , maintainable. careful choose namespaces wisely.


Comments

Popular posts from this blog

java - Plugin org.apache.maven.plugins:maven-install-plugin:2.4 or one of its dependencies could not be resolved -

Round ImageView Android -

How can I utilize Yahoo Weather API in android -