将字符串转换为模板字符串

时间:2015-03-21 11:34:21

标签: javascript ecmascript-6 eval template-strings

是否可以将模板字符串创建为通常的字符串

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

然后将其转换为模板字符串

let b=10;
console.log(a.template());//b:10

没有evalnew Function和其他动态代码生成方式?

19 个答案:

答案 0 :(得分:60)

由于你的模板字符串必须动态地(在运行时)引用b变量,所以答案是: NO,没有动态代码生成就不可能。

但是使用eval非常简单:

let tpl = eval('`'+a+'`');

答案 1 :(得分:36)

在我的项目中,我使用ES6创建了类似的内容:



String.prototype.interpolate = function(params) {
  const names = Object.keys(params);
  const vals = Object.values(params);
  return new Function(...names, `return \`${this}\`;`)(...vals);
}

const template = 'Example text: ${text}';
const result = template.interpolate({
  text: 'Foo Boo'
});
console.log(result);




<强>更新 我已经删除了lodash依赖项,ES6有相同的方法来获取键和值。

答案 2 :(得分:29)

你在这里要求的是什么:

//non working code quoted from the question
let b=10;
console.log(a.template());//b:10

eval完全等效(就权力和呃安全性而言):获取包含代码的字符串并执行该代码的能力;以及执行代码在调用者环境中查看局部变量的能力。

JS中没有办法让函数在其调用者中查看局部变量,除非该函数是eval()。即使Function()也无法做到。


当你听到JavaScript中出现了一些名为“模板字符串”的东西时,很自然地认为它是一个内置的模板库,比如Mustache。事实并非如此。它主要只是string interpolation和JS的多行字符串。不过,我认为这将是一个常见的误解。 :(

答案 3 :(得分:25)

不,没有动态代码生成,没有办法做到这一点。

但是,我创建了一个函数,它将常规字符串转换为一个函数,该函数可以在内部使用模板字符串提供值的映射。

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;
})();

用法:

var kingMaker = generateTemplateString('${name} is king!');

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

希望这有助于某人。如果您发现代码有问题,请更新Gist。

答案 4 :(得分:8)

TLDR: https://jsfiddle.net/w3jx07vt/

每个人似乎都担心访问变量,为什么不通过它们呢?我确信在调用者中获取变量上下文并将其传递下去并不会太难。使用此https://stackoverflow.com/a/6394168/6563504从obj获取道具。我现在不能为你测试,但这应该有效。

function renderString(str,obj){
    return str.replace(/\$\{(.+?)\}/g,(match,p1)=>{return index(obj,p1)})
}

测试。这是完整的代码。

function index(obj,is,value) {
    if (typeof is == 'string')
        is=is.split('.');
    if (is.length==1 && value!==undefined)
        return obj[is[0]] = value;
    else if (is.length==0)
        return obj;
    else
        return index(obj[is[0]],is.slice(1), value);
}

function renderString(str,obj){
    return str.replace(/\$\{.+?\}/g,(match)=>{return index(obj,match)})
}

renderString('abc${a}asdas',{a:23,b:44}) //abc23asdas
renderString('abc${a.c}asdas',{a:{c:22,d:55},b:44}) //abc22asdas

答案 5 :(得分:7)

这里的问题是拥有一个可以访问其调用者变量的函数。这就是我们看到直接eval用于模板处理的原因。一种可能的解决方案是生成一个函数,该函数采用由字典属性命名的形式参数,并以相同的顺序使用相应的值调用它。另一种方法是让事情变得简单:

var name = "John Smith";
var message = "Hello, my name is ${name}";
console.log(new Function('return `' + message + '`;')());

对于使用Babel编译器的任何人,我们需要创建一个闭包来记住创建它的环境:

console.log(new Function('name', 'return `' + message + '`;')(name));

答案 6 :(得分:5)

您可以使用字符串原型,例如

String.prototype.toTemplate=function(){
    return eval('`'+this+'`');
}
//...
var a="b:${b}";
var b=10;
console.log(a.toTemplate());//b:10

但原始问题的答案绝不可能。

答案 7 :(得分:5)

与Daniel的答案(和s.meijer的gist)类似,但更具可读性:

const regex = /\${[^{]+}/g;

export default function interpolate(template, variables, fallback) {
    return template.replace(regex, (match) => {
        const path = match.slice(2, -1).trim();
        return getObjPath(path, variables, fallback);
    });
}

//get the specified property or nested property of an object
function getObjPath(path, obj, fallback = '') {
    return path.split('.').reduce((res, key) => res[key] || fallback, obj);
}

注意:这略微改善了s.meijer的原创,因为它不匹配${foo{bar}之类的东西(正则表达式只允许${内的非大括号字符和{ {1}})。

更新:我被问到一个使用它的例子,所以你走了:

}

答案 8 :(得分:4)

我需要这种方法,支持Internet Explorer。事实证明,甚至IE11都不支持后退。也;使用eval或等效的Function感觉不对。

注意的人;我也使用反引号,但是像babel这样的编译器会删除这些反引号。其他方法建议的方法在运行时依赖于它们。如前所述;这是IE11及更低版本中的问题。

所以这就是我想出来的:

function get(path, obj, fb = `$\{${path}}`) {
  return path.split('.').reduce((res, key) => res[key] || fb, obj);
}

function parseTpl(template, map, fallback) {
  return template.replace(/\$\{.+?}/g, (match) => {
    const path = match.substr(2, match.length - 3).trim();
    return get(path, map, fallback);
  });
}

示例输出:

const data = { person: { name: 'John', age: 18 } };

parseTpl('Hi ${person.name} (${person.age})', data);
// output: Hi John (18)

parseTpl('Hello ${person.name} from ${person.city}', data);
// output: Hello John from ${person.city}

parseTpl('Hello ${person.name} from ${person.city}', data, '-');
// output: Hello John from -

答案 9 :(得分:3)

我目前无法对现有答案发表评论,因此我无法直接评论Bryan Raynor的出色回应。因此,这种反应将通过略微修正来更新他的答案。

简而言之,他的函数无法实际缓存创建的函数,因此它总是会重新创建,无论之前是否看过模板。这是更正后的代码:

    /**
     * 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 = cache[template] = Function('map', `return \`${sanitized}\``);
            }

            return fn;
        };

        return generateTemplate;
    })();

答案 10 :(得分:2)

我喜欢s.meijer的回答,并根据他自己的版本编写了自己的版本:

function parseTemplate(template, map, fallback) {
    return template.replace(/\$\{[^}]+\}/g, (match) => 
        match
            .slice(2, -1)
            .trim()
            .split(".")
            .reduce(
                (searchObject, key) => searchObject[key] || fallback || match,
                map
            )
    );
}

答案 11 :(得分:2)

@Mateusz Moska,解决方案效果很好,但是当我在React Native(构建模式)中使用它时,它会抛出一个错误:无效字符''',虽然它在我运行它时有效调试模式。

所以我用正则表达式写下了我自己的解决方案。

String.prototype.interpolate = function(params) {
  let template = this
  for (let key in params) {
    template = template.replace(new RegExp('\\$\\{' + key + '\\}', 'g'), params[key])
  }
  return template
}

const template = 'Example text: ${text}',
  result = template.interpolate({
    text: 'Foo Boo'
  })

console.log(result)

演示: https://es6console.com/j31pqx1p/

注意:由于我不知道问题的根本原因,我在react-native repo https://github.com/facebook/react-native/issues/14107中提出了一张票,这样一旦他们能够修复/指导我一样:)

答案 12 :(得分:2)

仍然是动态的,但似乎比仅使用裸eval更受控制:

$("#Divnavigation").html("<p>test</p>)

https://repl.it/IdVt/3

答案 13 :(得分:1)

这里发布了很多好的解决方案,但是还没有一个利用ES6 String.raw method的解决方案。这是我的贡献。它有一个重要的限制,那就是它只能接受传入对象的属性,这意味着模板中的任何代码执行都无法工作。

function parseStringTemplate(str, obj) {
    let parts = str.split(/\$\{(?!\d)[\wæøåÆØÅ]*\}/);
    let args = str.match(/[^{\}]+(?=})/g) || [];
    let parameters = args.map(argument => obj[argument] || (obj[argument] === undefined ? "" : obj[argument]));
    return String.raw({ raw: parts }, ...parameters);
}
let template = "Hello, ${name}! Are you ${age} years old?";
let values = { name: "John Doe", age: 18 };

parseStringTemplate(template, values);
// output: Hello, John Doe! Are you 18 years old?
  1. 将字符串拆分为非参数的文本部分。参见regex
    parts: ["Hello, ", "! Are you ", " years old?"]
  2. 将字符串拆分为属性名称。如果匹配失败,则为空数组。
    args: ["name", "age"]
  3. 根据属性名称映射obj中的参数。解决方案受到浅层映射的限制。未定义的值将替换为空字符串,但可以接受其他伪造的值。
    parameters: ["John Doe", 18]
  4. 使用String.raw(...)并返回结果。

答案 14 :(得分:0)

此解决方案无需ES6即可运行:

function render(template, opts) {
  return new Function(
    'return new Function (' + Object.keys(opts).reduce((args, arg) => args += '\'' + arg + '\',', '') + '\'return `' + template.replace(/(^|[^\\])'/g, '$1\\\'') + '`;\'' +
    ').apply(null, ' + JSON.stringify(Object.keys(opts).reduce((vals, key) => vals.push(opts[key]) && vals, [])) + ');'
  )();
}

render("hello ${ name }", {name:'mo'}); // "hello mo"

注意:Function构造函数始终在全局范围内创建,这可能会导致全局变量被模板覆盖,例如: render("hello ${ someGlobalVar = 'some new value' }", {name:'mo'});

答案 15 :(得分:0)

因为我们正在重新发明关于javascript中一个可爱功能的东西。

我使用eval(),这不安全,但javascript不安全。我很乐意承认我在javascript方面并不出色,但我有需要,而且我需要一个答案,所以我做了一个。

我选择使用@而不是$来设置我的变量的样式,特别是因为我想使用文字的多行功能而不用进行评估直到&#39;准备好了。所以变量语法是@{OptionalObject.OptionalObjectN.VARIABLE_NAME}

我不是javascript专家,所以我很乐意接受改进方面的建议但是......

var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g
for(i = 0; i < myResultSet.length; i++) {
    prsLiteral = rt.replace(prsRegex,function (match,varname) {
        return eval(varname + "[" + i + "]");
        // you could instead use return eval(varname) if you're not looping.
    })
    console.log(prsLiteral);
}

一个非常简单的实现

&#13;
&#13;
myResultSet = {totalrecords: 2,
Name: ["Bob", "Stephanie"],
Age: [37,22]};

rt = `My name is @{myResultSet.Name}, and I am @{myResultSet.Age}.`

var prsLiteral, prsRegex = /\@\{(.*?)(?!\@\{)\}/g
for(i = 0; i < myResultSet.totalrecords; i++) {
    prsLiteral = rt.replace(prsRegex,function (match,varname) {
        return eval(varname + "[" + i + "]");
        // you could instead use return eval(varname) if you're not looping.
    })
    console.log(prsLiteral);
}
&#13;
&#13;
&#13;

在我的实际实施中,我选择使用@{{variable}}。还有一套大括号。绝对不可能意外地遇到这种情况。正则表达式看起来像/\@\{\{(.*?)(?!\@\{\{)\}\}/g

使其更容易阅读

\@\{\{    # opening sequence, @{{ literally.
(.*?)     # capturing the variable name
          # ^ captures only until it reaches the closing sequence
(?!       # negative lookahead, making sure the following
          # ^ pattern is not found ahead of the current character
  \@\{\{  # same as opening sequence, if you change that, change this
)
\}\}      # closing sequence.

如果您没有使用正则表达式,那么一个非常安全的规则就是逃避每个非字母数字字符,并且不要永远不必要地转义字母,因为许多转义字母都有特殊字母对几乎所有正则表达式都有意义。

答案 16 :(得分:0)

您应该尝试从github下载的Andrea Giammarchi编写的这个小JS模块: https://github.com/WebReflection/backtick-template

/*! (C) 2017 Andrea Giammarchi - MIT Style License */
function template(fn, $str, $object) {'use strict';
  var
    stringify = JSON.stringify,
    hasTransformer = typeof fn === 'function',
    str = hasTransformer ? $str : fn,
    object = hasTransformer ? $object : $str,
    i = 0, length = str.length,
    strings = i < length ? [] : ['""'],
    values = hasTransformer ? [] : strings,
    open, close, counter
  ;
  while (i < length) {
    open = str.indexOf('${', i);
    if (-1 < open) {
      strings.push(stringify(str.slice(i, open)));
      open += 2;
      close = open;
      counter = 1;
      while (close < length) {
        switch (str.charAt(close++)) {
          case '}': counter -= 1; break;
          case '{': counter += 1; break;
        }
        if (counter < 1) {
          values.push('(' + str.slice(open, close - 1) + ')');
          break;
        }
      }
      i = close;
    } else {
      strings.push(stringify(str.slice(i)));
      i = length;
    }
  }
  if (hasTransformer) {
    str = 'function' + (Math.random() * 1e5 | 0);
    if (strings.length === values.length) strings.push('""');
    strings = [
      str,
      'with(this)return ' + str + '([' + strings + ']' + (
        values.length ? (',' + values.join(',')) : ''
      ) + ')'
    ];
  } else {
    strings = ['with(this)return ' + strings.join('+')];
  }
  return Function.apply(null, strings).apply(
    object,
    hasTransformer ? [fn] : []
  );
}

template.asMethod = function (fn, object) {'use strict';
  return typeof fn === 'function' ?
    template(fn, this, object) :
    template(this, fn);
};

演示(以下所有测试均返回true):

const info = 'template';
// just string
`some ${info}` === template('some ${info}', {info});

// passing through a transformer
transform `some ${info}` === template(transform, 'some ${info}', {info});

// using it as String method
String.prototype.template = template.asMethod;

`some ${info}` === 'some ${info}'.template({info});

transform `some ${info}` === 'some ${info}'.template(transform, {info});

答案 17 :(得分:0)

我做了自己的解决方案,以描述为函数来做类型

export class Foo {
...
description?: Object;
...
}

let myFoo:Foo = {
...
  description: (a,b) => `Welcome ${a}, glad to see you like the ${b} section`.
...
}

然后这样做:

let myDescription = myFoo.description('Bar', 'bar');

答案 18 :(得分:-1)

用于正则表达式而不是更好地使用eval

建议不要使用它,也不建议使用它,因此请不要使用它(mdn eval)。

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

let response = a.replace(/\${\w+}/ ,b);
conssole.log(response);