Home > Mobile >  jinja2.exceptions.UndefinedError: 'asset' is undefined
jinja2.exceptions.UndefinedError: 'asset' is undefined

Time:12-11

I am fetching API data through my Python backend which I then render through Flask to my Vue.js frontend. However, I am getting the error in the title.

I have checked and printed the variable I am trying to pass, and it prints the content of the list fine.

This is how I render the variable from Python:

def index():
    # Get the assets data
    assets = get_assets()
    
    # Return the template with the assets data
    return render_template("index.html", asset_data=assets)

And this is how I have it setup in my HTML file. First I run through the list using v-for:

                <tr v-for="asset in assets">
                    <td>{{ asset.name }}</td>
                    <td>{{ asset.symbol }}</td>
                </tr>

And I have this JS script:

        <script>
            const app = new Vue({
                el: "#app",
                data: {
                assets: {{ asset_data }}
                }
            });
        </script>

My list looks like this:

                    {
                        "name": "Asset 1",
                        "symbol": "A1",
                    },
                    {
                        "name": "Asset 2",
                        "symbol": "A2",

                    },
                    {
                        "name": "Asset 3",
                        "symbol": "A2",

                    } ......

Could someone please help me out?

Thank you!

CodePudding user response:

Assuming that your asset_data list is valid JSON, you most likely need to redefine the delimiters used in Vue:

const app = new Vue({
    el: '#app',
    data: {
        assets: {{ asset_data }},
    },
    delimiters: ['[[',']]']
});

And then in your Vue HTML, you can use this [[ ]] delimiter:

<tr v-for="asset in assets">
    <td>[[ asset.name ]]</td>
    <td>[[ asset.symbol ]]</td>
</tr>

As you know, Jinja and Vue use the same double curly brace delimiter by default ({{ }}), and as a consequence, Jinja was interpreting your Vue variable ({{ asset.name }}) as a Jinja variable.

Another alternative without redefining the Vue delimiters, is to just wrap the Jinja {% raw %} tag around your Vue variables:

<tr v-for="asset in assets">
    <td>{% raw %}{{ asset.name }}{% endraw %}</td>
    <td>{% raw %}{{ asset.symbol }}{% endraw %}</td>
</tr>

This tells Jinja to ignore parts of your template.

Hope this helps.

  • Related