简体   繁体   English

Javascript 模板字符串占位符

[英]Javascript template string placeholders

Is it possible to create a template string in javascript with placeholders to be filled in later, a la python?是否可以在 javascript 中创建一个模板字符串,并在以后填充占位符,la python?

for example, in python, I could do something like this:例如,在 python 中,我可以做这样的事情:

def makeApiFunction(endpoint, requestFunction):

    def func(**params):
        return requestFunction(endpoint.format(**params))

    return func

and use it like so:并像这样使用它:

 someApiFunc = makeApiFunction('/api/v1/my/endpoint/{pk}/with/{random}/vars/', other_module.get)

 ### somewhere else
 someApiFunc(pk=1, random='some')

I suppose I could do something like this in javascript:我想我可以在 javascript 中做这样的事情:

function makeApiFunction(endpoint) {
    return (params) => {
        Object.keys(params).map(key => {
           endpoint = endpoint.replace(`{${key}}`, params[key])
         })
 }

Is there a better way (something in-built I dont know about perhaps?)有没有更好的方法(我可能不知道内置的东西?)

You should use external library for string templates.您应该将外部库用于字符串模板。 For instance you can take a look at Lodash例如,您可以查看Lodash

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM