javascriptpythondjangofirebasefirepad

firepad: a variable as the default text in firepad's codemirror div


I am integrating firepad with my django project. I dont have much expertise in javascript and I am facing an issue due to that.

If I follow all the steps, everything seems to be working fine.

<script>
    //// Initialize Firebase.
    //var firepadRef = getExampleRef();
    // TODO: Replace above line with:
     var ref = new Firebase('<YOUR FIREBASE URL>');

    //// Create CodeMirror (with line numbers and the JavaScript mode).
    var codeMirror = CodeMirror(document.getElementById('firepad-container'), {
      lineNumbers: true,
      mode: 'javascript'
    });

    //// Create Firepad.
    var firepad = Firepad.fromCodeMirror(firepadRef, codeMirror);

    //// Initialize contents.
    firepad.on('ready', function() {
      if (firepad.isHistoryEmpty()) {
        firepad.setText('// JavaScript Editing with Firepad!\nfunction go() {\n var message = "Hello, world.";\n console.log(message);\n}');
      }
    });
  </script>

However I have a dictionary variable named 'user' on the page rendered through a django view.

and I want to use this variable in the above example as {{user.textkey}} instead of a fixed default text. textkey points to a text.

user = {'textkey':text}

something like this:-

firepad.setText('{{user.textkey}}');

I hope you get my point. The issue here is that the text may contain anything like an apostrophe or unicode characters (like left or right single quotation mark) etc. Also django replaces \n in the variable and results in a format not supported in javascript.

For example:-

if text contains

Hello \xe2\x80\x98World\xe2\x80\x99:\n Good morning:\n 

then

firepad.setText('{{user.textkey}}');

will look like this

firepad.setText('{{Hello 'World'
Good morning
}}');

which wont be understood by javascript.

How to tackle this?

Any kind of suggestions are welcome.


Solution

  • You could try

    firepad.setText('{{user.textkey | escapejs}}')
    

    which I found documented here.