Search code examples
javascriptblocklygoogle-blockly

Composing complex code as string in javascript


I'm designing custom Blockly blocks with their own JavaScript code, when the code I'm trying to output as string is a one liner, that's not so complicated but when the code I'm trying to associate to my custom block, doing it by concatenation of variables, single, double quotes it starts being messy and produces code with syntax errors that is hard to troubleshoot.

Here's code for a simple block, the way I do it now:

this.EnableAllItems = function (block) {
    var target_field = block.getField('target_field');
    var code = "$('#" + target_field.getText() + " option').removeAttr('disabled');\r\n";
    return code;
}

This is a block I use to enable all options in a select input.

Works for simple code. But what I'd like to be able to do is compose the JS code literally and have it converted to string later on.

Would something like this be possible:

function enableItemsLogic(targetField) {
    $('#' + targetField + ' option').removeAttr('disabled'); 
} 

this.EnableAllItems = function (block) {
    var target_field = block.getField('target_field');
    //somehow return the above function as code with the literal parameter filled in ?
    var code = enableItemsLogic(target_field.getText());
    return code;
}

Are there any JS tricks that would allow me to do that?


Solution

  • You can use template literals for this (if you transpile your JavaScript, it's an ES5 feature).

    const name = "Francis";
    const foo = `Hello my name is: ${name}`;
    

    Read more here: https://developer.mozilla.org/nl/docs/Web/JavaScript/Reference/Template_literals