0

I am using GAE and at some stage I decode a UTF8 string to then hand it over to an HTML file with Jinja2:

  for i in report:
        unique_channels.append(i[0][j].decode("utf8"))

    template_values = {
        "unique_channels" : unique_channels,
        "result" : result
    }

Now, when I use Jinja2 to iterate over this list of unicode strings, all is good. But when I pass this list to Javascript, Javascript throws an unexpected string error. I assume the reason is the u'xxx'/Unicode strings.

var unique_channels = {{ unique_channels }};

for (var i = 1; i < 11; i++) {
   new_data.push({"Position" : i.toString()})
    for (var k = unique_channels.length - 1; k >= 0; k--) {
      new_data[i-1][unique_channels[k]] = 0;
    } 
};

How do I avoid this? Should I pass the list to javascript in a different way? Any suggestions?

EDIT: Second part where I use the unique_channels list:

{% for j in unique_channels %}
<br><input type="checkbox" class="checkbox" name="{{ j }}" value="{{ j }}" onclick="updateData();" checked> {{ j }}
{% endfor %}

This will be treated as string when I use json.dumps

1 Answer 1

2

Serialize the data using json.dumps before pass to the template:

  for i in report:
        unique_channels.append(i[0][j].decode("utf8"))

    template_values = {
        "unique_channels" : json.dumps(unique_channels),
        "result" : result
    }

And use safe filter in the template to prevent escape:

var unique_channels = {{ unique_channels|safe }};

for (var i = 1; i < 11; i++) {
   new_data.push({"Position" : i.toString()})
    for (var k = unique_channels.length - 1; k >= 0; k--) {
      new_data[i-1][unique_channels[k]] = 0;
    } 
};
Sign up to request clarification or add additional context in comments.

6 Comments

json.dumps creates a string though, doesn't it? So if I iterate over this, I'll get the letters of the string, not the strings in the list. Any idea how to work around this?
@oliver13, If you use the passed unique_channels in other place in the template, pass non-serialized version also.
@oliver13, In javascript, unique_channels is an array, not a string. Check it out.
@oliver13, I mean: template_values = {"unique_channels_py": unique_channels, "unique_channels": json.dumps(unique_channels), "result" : result}
Ok, makes sense... still this throws me an unexpected end of input for the var unique_channels = unique_channels|safe. Any idea what this could relate to?
|

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.