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

时间:2017-02-16 01:18:05

标签: javascript ecmascript-6 mustache

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

胡子或类似的东西似乎是一个竞争者,但我想知道替换是否不完整。在这种情况下,它会生成网址,因此缺少的部分意味着无效的网址:

在节点中测试它:

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'

1 个答案:

答案 0 :(得分:0)

我最终使用了sprintf,它的好处是具有与Mustache(或Django)不同的格式,因此您可以将其嵌入#create the MSSQL connection with python table_one_connection = pypyodbc.connect(driver="{SQL Server}", server="xxx.xxx.xxx.xxx", uid="you-cant-see-me", pwd="guessme",Trusted_Connection = "No") #set the cursor for table_one cursor = table_one_connection.cursor() cursor.execute("[data].[Tableschema].[DEFINED_SP] @start_date='xx-xx-xx', @end_date='xx-xx-xx'") #Fetching data cursor.fetchall() #Create the workbook of results print("Generating the workbooks with the database data") cursor_results_workbook = xlwt.Workbook() results_sheet = cursor_results_workbook.add_sheet("SP values") #row counter that you use to move from rows row_counter = 0 #write the data onto the Excel file for index,value in enumerate(cursor): try: #extract from the tuple 'results' the value of each item and store it in every column for all rows results_sheet.write(row_counter, 0, value[0]) results_sheet.write(row_counter, 1, value[1]) results_sheet.write(row_counter, 2, value[2]) results_sheet.write(row_counter, 3, value[3]) results_sheet.write(row_counter, 4, value[4]) except: print("Error in line %s\n data=%s" % (index, value)) row_counter = row_counter + 1 cursor.close() 之类:

y =  bitxor (10100010,01000101 )

输出:

data-url