-1

I want to dynamically change a JavaScript file in the static folder of my Flask application.

I'm aware that Jinja2 can dynamically change my HTML file with {{ var1 }} and render_template(file.html, var1 = x), but I want Flask to reach into the scripts the HTML imports and change them as well, without the JavaScript having to be in the HTML template.

Does Flask support this, or do I just have to put the JavaScript I want to change dynamically into the HTML file and use render_template?

1
  • 2
    You want to dynamically change static files? There is something wrong with that. But jinja does not care if you generate html or js files. You must register a route for you dynsmic js files and then you can serve them like the dynamic html files. Commented Mar 30, 2016 at 14:45

1 Answer 1

2

No. You will have to move the dynamic parts of your JavaScript into the html file.

When Jinja2 renders a template file the only file being read is the one specified by render_template. In your case that is file.html. In other words, flask only serves up the HTML. Your static JS file is probably served by flask, it is not processed by the template engine.

The cleanest solution would likely be to call an init function to initialize whatever variables you want set from the html like so:

<script type="text/javascript" src="/static/sripts/example.js" />
<script type="text/javascript">
    exampleInitFunction({{var1}});
</script> 
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.