Wade Cong
Wade Cong

Reputation: 13

How to pass variables to assets in Flask

I'm using Flask to build a website. I also use assets to manage my js and css resources. Now I want to pass some variables to my js scripts.

here is the code I register assets when the flask init(__init__.py):

download_js = Bundle("applog/download.coffee", filters=["jinja2", "coffeescript"],
                 output="gen/js/download.js")
assets.register("download_js", download_js)

here is the code I use the asset in my template file(download.html):

{% assets "download_js" %}
    <script>
        require(["{{ ASSET_URL}}"]);
    </script>
{% endassets %}

and in view file("view.py"), I pass the varibales like this:

return render_template("download.html", apps=apps, versions=versions)

and I want to use the variable "apps" in the js file like this:

DownLoadSelector("appList", {{ apps }})

How can I do that?

Upvotes: 1

Views: 737

Answers (1)

iurisilvio
iurisilvio

Reputation: 4987

Your assets are static, you can't change it in an easy way. You can add a filter to webassets, but it is a weird hack.

To do what you want, you can do it:

{% assets "download_js" %}
    <script>
        window.apps = {{ apps }};
        require(["{{ ASSET_URL}}"]);
    </script>
{% endassets %}

In your code, you just call apps:

DownLoadSelector("appList", window.apps)

Upvotes: 1

Related Questions