Convert a string to a template string

前端 未结 19 2166
轮回少年
轮回少年 2020-11-22 08:30

Is it possible to create a template string as a usual string

let a=\"b:${b}\";

an then convert it into a template string

le         


        
19条回答
  •  花落未央
    2020-11-22 09:13

    No, there is not a way to do this without dynamic code generation.

    However, I have created a function which will turn a regular string into a function which can be provided with a map of values, using template strings internally.

    Generate Template String Gist

    /**
     * Produces a function which uses template strings to do simple interpolation from objects.
     * 
     * Usage:
     *    var makeMeKing = generateTemplateString('${name} is now the king of ${country}!');
     * 
     *    console.log(makeMeKing({ name: 'Bryan', country: 'Scotland'}));
     *    // Logs 'Bryan is now the king of Scotland!'
     */
    var generateTemplateString = (function(){
        var cache = {};
    
        function generateTemplate(template){
            var fn = cache[template];
    
            if (!fn){
                // Replace ${expressions} (etc) with ${map.expressions}.
    
                var sanitized = template
                    .replace(/\$\{([\s]*[^;\s\{]+[\s]*)\}/g, function(_, match){
                        return `\$\{map.${match.trim()}\}`;
                        })
                    // Afterwards, replace anything that's not ${map.expressions}' (etc) with a blank string.
                    .replace(/(\$\{(?!map\.)[^}]+\})/g, '');
    
                fn = Function('map', `return \`${sanitized}\``);
            }
    
            return fn;
        }
    
        return generateTemplate;
    })();
    

    Usage:

    var kingMaker = generateTemplateString('${name} is king!');
    
    console.log(kingMaker({name: 'Bryan'}));
    // Logs 'Bryan is king!' to the console.
    

    Hope this helps somebody. If you find a problem with the code, please be so kind as to update the Gist.

提交回复
热议问题