Pass parameter with Python flag in external Javascript

I use Python Flask for my site, and I pass in a few Javascript parameters. This is my code:

from flask import Flask from flask import render_template app = Flask(__name__) @app.route("/") def index(): return render_template("index.html", param1="Hello") <html> <head> </head> <body> <p>Hello World</p> </body> <script>console.log({{param1}})</script> </html> 

Thus, it works without problems. This example is simplified. But, if I want to have a script in an external file and name it like this:

 <html> <head> </head> <body> <p>Hello World</p> </body> <script src="/static/js/myjs.js"></script> </html> 

And the myjs.js file is console.log({{param1}}) , then it does not work. So, is there a way to pass parameters in external Javascript files using Python Flask?

+8
javascript python flask
source share
2 answers

If you want to display a file using Jinja, you need to call render_template on it and pass it the desired values. Obviously, this is not due to a direct link to a static file. One solution is to use the Jinja include block. This requires that "myjs.js" be in the "templates / js" folder and will include it in the rendered template, passing the entire template context to the included template.

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

The solution better does not require js rendering for each request and instead passes parameters to js functions from your template.

 <script src="{{ url_for('static', filename='js/myjs.js') }}"></script> <script> my_func({{ my_var|tojson }}); </script> 
+12
source share

I used another way to load the javascript file specified on the html page:

First, I define some variables inside the <head></head> tags, so I call my javascript file:

 <head> ... <script src="/static/js/jquery.js"></script> <script type=text/javascript> $(document).ready(function() { $link_subcat = "{{ url_for('load_subcategories') }}"; $link_cat = "{{ url_for('load_categories') }}"; }); </script> <script src="{{ url_for('static', filename='finances.js') }}"></script> 

...

This is my javascript content: $ (document) .ready (function () {

  $("#category").change(function() { $.ajax({ type: "POST", url: $link_subcat, data: {cat: $(this).val()}, success: function(data) { $("#subcategory").html(data); } }); }); $("input[name=type]").change(function() { $.ajax({ type: "POST", url: $link_cat, data: {type: $('input[name="type"]:checked').val()}, success: function(data) { $("#category").html(data); } }); }); }); 

This approach works for me.

0
source share

All Articles