javascript - 替换为字符串模板,但捕获丢失的变量

标签 javascript ecmascript-6 mustache

我想对字符串执行变量替换(我已经排除了模板文字,因为必须稍后存储和评估字符串)。

mustache 或类似的东西看起来像是一个竞争者,但我想知道替换是否不完整。在本例中,它是为了生成 url,因此缺少部分意味着无效的 url:

在节点中测试这一点:

var Mustache  = require('mustache');
var result = Mustache.render("/someurl/{{path1}}/{{path2}}/", {path1:"my-path-to-1"})
console.log(`result:${result}:`)

这种情况发生时没有问题,但生成的 url 毫无用处,因为 Mustache 默默地用空字符串替换了丢失的 path2。我希望看到的是抛出异常(最好)或失败,这是一种简单的方法来认识到并非所有内容都被替换。

注意:模板字符串是任意的,替换对象的内容也是任意的。

输出:

result:/someurl/my-path-to-1//:

这是我正在寻找的 Python 等效项:

res = "/someurl/%(path1)s/%(path2)s/" % {"path1":"my-path-to-1"}

输出:

KeyError: 'path2'

最佳答案

我最终使用了 sprintf,它的优点是具有与 Mustache(或 Django)不同的格式,以便您可以将其嵌入到 data-url 等中:

const sprintf = require("sprintf-js").sprintf;

var o_substit = {
  path1 : "mypath1"
};

var T_URL = "/someurl/%(path1)s/%(path2)s/";


console.log(`\nT_URL:${T_URL}, substitutions:`);
try {
  console.dir(o_substit);
  console.log("expecting a failure...")
  var url = sprintf(T_URL, o_substit);
  console.log(`  url:${url}:`);
}
catch (e){
  console.log(`  exception:${e}`);  
};

var o_substit = {
  path1 : "mypath1"
  ,path2 : "mypath2"
};


console.log(`\nT_URL:${T_URL}, substitutions:`);
try{
  console.dir(o_substit);
  console.log("\nexpecting a success:")
  var url = sprintf(T_URL, o_substit);
  console.log(`  url:${url}:`);
}
catch (e){
  console.log(`  exception:${e}`);  
};

输出:

T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1' }
expecting a failure...
  exception:Error: [sprintf] property 'path2' does not exist

T_URL:/someurl/%(path1)s/%(path2)s/, substitutions:
{ path1: 'mypath1', path2: 'mypath2' }

expecting a success:
  url:/someurl/mypath1/mypath2/:

关于javascript - 替换为字符串模板,但捕获丢失的变量,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42263122/

相关文章:

javascript - 是否可以更改代理的目标?

javascript - ES6 相当于 lodash _.mapValues

mustache - 如何处理 mustache 模板中的字符串或字符串数​​组

javascript - 如何使字体很棒的图标可点击事件

javascript - 是否可以使用 href "Go Back"通过我的 ='javascript:history.go(-1)' 按钮发送变量

javascript - 如何在 React Native 的 StyleSheet.create 中继承样式(可能使用解构语法)

javascript - mustache 格式的 Backbone /下划线模板导致#磅/哈希符号出错?

ruby - 如何在使用 ERB 作为主要模板引擎时在 Sinatra 中渲染 Mustache 部分

javascript - 下载二进制格式的字节数组

javascript - 从表单文本字段获取值