Login

Generate Javascript-Safe string in template

Author:
SpikeekipS
Posted:
February 25, 2007
Language:
Python
Version:
Pre .96
Score:
-1 (after 5 ratings)

If you use javascript code with Django-template filter or other related things, it will be not sufficient to qoute string in javascript. This filter escape the string and quote it.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
import os
from django.template.defaultfilters import escape

@register.filter(name="tojavascript")
def tojavascript (value) :
	if len(value.split(os.linesep)) > 1 :
		__s = ["\"%s\"" % escape(i) for i in value.split(os.linesep)]
		return "%s\n%s" % (__s[0], "\n".join([" + %s" % i for i in __s[1:]]), )
	else :
		return "\"%s\"" % escape(value)

More like this

  1. Template tag - list punctuation for a list of items by shapiromatron 3 months, 1 week ago
  2. JSONRequestMiddleware adds a .json() method to your HttpRequests by cdcarter 3 months, 2 weeks ago
  3. Serializer factory with Django Rest Framework by julio 10 months, 1 week ago
  4. Image compression before saving the new model / work with JPG, PNG by Schleidens 11 months ago
  5. Help text hyperlinks by sa2812 11 months, 3 weeks ago

Comments

guychi (on August 26, 2007):

doesn't seem to work.

the code is also exceedingly unclear, perhaps you'd care to explain it a bit?

#

Please login first before commenting.