0

I'm using Bottle and Python 2.7.

I would like to pass a list variable from my Bottle's controller to the view page, where it will be used in a JavaScript variable.

@app.route('/foo'):
def foo():
    l = [{'name':'Matthew'}]
    return template('foo', l=l)

I've also done:

l = json.dumps([{'name':'Matthew'}]

In my view

<script type="text/javascript">
    $(document).ready({
        var l = {{l}}
        l.forEach(function(entry) {
            console.log(entry);
        });
    });
</script>

However my console says I have a syntax error. When I open the HTML, it is rendered like:

var l = [{&quot;name&quot;: &quot;Matthew&quot;]

How can I transfer a python object for use in a JavaScript variable?

2 Answers 2

1

The substitutions between {{ and }} are HTML Entity encoded to prevent XSS amongst other things.

Try this:

var l = {{!l}};
Sign up to request clarification or add additional context in comments.

2 Comments

Is it unsafe if I do this?
It's unsafe if l was user-generated content. It's not unsafe if you know that l contains only valid JSON.
1

Bottle (via, the SimpleTemplate engine) is escaping the output to prevent XSS vulnerability. This is good, generally. You can disable the escaping temporarily using ! like:

var l = {{!l}};

The docs for it are here

2 Comments

Is it unsafe if I do this?
It's safest to assume not, hence it being escaped by default. It can be though, depending on the source of the data. If it comes from a trusted source, such as a developer or (maybe) an admin, it might be okay. Otherwise, no.

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.