17

I use Python Flask for my website and I pass several parameters to Javascript. 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>

With this way, it works without a problem. The example is a simplified of my own. But, if I want to have the script on an external file and call 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 the console.log({{param1}}), then it doesn't work. So, is there any way to pass parameters in external Javascript files with Python Flask?

2
  • script must be inside template directory Commented Jan 13, 2015 at 8:09
  • 1
    I have two folders: 1) static and 2) templates. In static folder there are css, js and images. Should I move the js files ijn templates to make it work? Commented Jan 13, 2015 at 9:17

2 Answers 2

22

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="{{ url_for('static', filename='js/myjs.js') }}"></script>
<script>
    my_func({{ my_var|tojson }});
</script>
Sign up to request clarification or add additional context in comments.

Comments

1

I used a different way to load a javascript file specified in html page:

Firstly, I define some variables inside <head></head> tags, and 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 file 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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.