Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

GAE + Javascript push : multiline to push

I have this in the Google App Engine python code,

class ABC(db.Model):
  StringA = db.StringProperty()
  StringB = db.StringProperty(multiline=True)

abcs = ABC.all()
template_values = {'abcs': abcs,}
path = os.path.join(os.path.dirname(__file__), 'index.html')
self.response.out.write(template.render(path, template_values))

and this in the index.html,

<script type="text/javascript">
 var string_A = [];
 var string_B = [];

{% for abc in abcs %}
 string_A.push("{{ abc.StringA }}");
 string_B.push("{{ abc.StringB }}");  //This doesn't work?
{% endfor %}
</script>

My question is that how to I push the multiline to the array??

Thanks in advance.

like image 764
Peter Avatar asked Jan 06 '11 13:01

Peter


1 Answers

If you are generating a Javascript expression, you need to be careful to escape the string so you always get a valid Javascript expression and you don't introduce a XSS vulnerability (in case the strings are provided by users). You can use the addslashes Django template filter to escape special chars for a Javascript string:

string_B.push("{{ abc.StringB|addslashes }}");

An alternative solution is to use json to generate a safe and properly escaped javascript expression containing all the data you'll need in the Javascript code. See this question about using json on GAE. Using json you can write something like:

from django.utils import simplejson as json
class ABC(db.Model):
    # [...]
    def as_json(self):
        return json.dumps({'StringA':self.StringA, 'StringB':self.StringB})

And at the template:

<script type="text/javascript">
var abcs = [];
{% for abc in abcs %}
abcs.push({{ abc.as_json }});
{% endfor %}
</script>

This way you get all the data you'll need from the abc objects in a single array.

like image 127
ehabkost Avatar answered Nov 15 '22 07:11

ehabkost