How can I pass parameter through serialization and then parse them using external JavaScript?

If you want to render a file with Jinja, you need to call render_template on it and pass it the desired values. Just linking directly to a static file obviously doesn’t do that. One solution is to use Jinja’s include block. This requires that ‘myjs.js’ is in the ‘templates/js’ folder, and will include it in the rendered template, passing all the templates context to the included template.

<script>{% include 'js/myjs.js' %}</script>

The better solution is to not require rendering the js on every request, and instead passing parameters to js functions from your template.

<script src="https://stackoverflow.com/questions/27917471/{{ url_for("static', filename="js/myjs.js") }}"></script>
<script>
    my_func({{ my_var|tojson }});
</script>

Leave a Comment

tech