1

I have a database field storing a chunk of xml that is used by another web application (ie not django-related). I need to take that chunk of xml and insert it into some javascript that the page is using.

In my template:

var netdata = "{% filter addslashes  %}{{netdata}}{% endfilter %}"

The variable netdata from my database looks like this this (multiline, and contains quotes). The "addslashes" filter takes care of the quotes, I think.

The above gives me "unterminated string literal" error. (Presumably because of the newline). What do I need to do to get that whole chunk of xml, newlines and all, into a valid javascript variable?

For more context, I am trying to use CytoscapeWeb. In the file compound.js used in that demo, they get data like this:

        $.get(url, function(dt) {
        if (typeof dt !== "string") {
            if (window.ActiveXObject) {
                dt = dt.xml;
            } else {
                dt = (new XMLSerializer()).serializeToString(dt);
            }
        }

where url is the same as above.

I am trying to do a similar thing, but pass in the data from my database via django template (skipping the whole "get external file" part).

(I don't want to mess with parsing the xml before storing in the db so please don't suggest that).

4

2 回答 2

2

您可能应该使用escapejs过滤器而不是添加斜杠。另请注意,您可以直接过滤变量:

var netdata = "{{ netdata|escapejs }}"
于 2013-10-02T18:11:43.263 回答
1

Your problem is that the generated javascript a "multiline string" which javascript cannot do unless you escape every new line like this:

var my_string = "hello \
                 world"

So, before you print the xml string, you could either replace every new line with a \ and a new line, or you could just remove the newlines altogether.

I believe the escapejs filter will do that for you. {{ netdata|escapejs }}

于 2013-10-02T18:17:55.040 回答