Special characters escaped in text block

298 views
Skip to first unread message

Bart Butenaers

unread,
Sep 20, 2018, 5:52:13 PM9/20/18
to Blockly
Hi folks,

Got a question from one of our users, who wants to generate a (Javascript) string containing termination characters (newline, carriage return, tabs, ...).
Currently these characters seem to be automatically escaped by the text block (i.e. extra \ prefix):

blockly_newline_code.png

Seems the text-block always applies escaping (via the 'quote_' function):

blockly_newline_generator.png


I'm wondering why these are always escaped, and if there is a (good) way to avoid this?


Thanks !
Bart

Amber Blaylock

unread,
Sep 21, 2018, 10:55:12 AM9/21/18
to Blockly
We actually ran into this in our setup. It seems like this is done automatically in Blockly. Our solution was just to make a special character block and add it in where needed using string concatenation. If you want to just wholesale borrow that solution, the code is here:


Blockly.Blocks['meta_characters'] = {
 init
: function () {
 
this.setOutput(true, 'String');
 
this.appendDummyInput('')
 
.appendField('Special character:')
 
.appendField(new Blockly.FieldDropdown([['Line Feed (\\n)', '\\n'], ['Carriage Return (\\r)', '\\r'], ['Carriage Return Line Feed (\\r\\n)', '\\r\\n'], ['Tab (\\t)', '\\t']]), 'character');
 
this.setColour(Blockly.Msg.TEXTS_HUE ? Blockly.Msg.TEXTS_HUE : Blockly.Blocks.texts.HUE);
 
this.setTooltip('');
 
this.setHelpUrl('');
 
}
};


Blockly.JavaScript['meta_characters'] = function (block) {
 
var code = '\'' + (block.getFieldValue('character') || '') + '\'';
 
return [code, Blockly.JavaScript.ORDER_ATOMIC];
};

Amber Blaylock

unread,
Sep 21, 2018, 11:04:25 AM9/21/18
to Blockly
As for why it's done, I believe that it's meant to prevent wise alecs from entering escaping sequences into a text block and forcing anything that executes the code from injecting arbitrary code of their own design.

Bart Butenaers

unread,
Sep 22, 2018, 3:21:30 AM9/22/18
to Blockly
Hi Amber,

Thanks a lot for sharing your solution !!
Your 'why' explanation also makes sense.

Kind regards,
Bart
Reply all
Reply to author
Forward
0 new messages