部分在Jsonnet中插值格式字符串

huangapple go评论83阅读模式
英文:

Partially interpolate a format string in Jsonnet

问题

假设我想要做:

local formatString = "Name: %(a)s Age: %(b)s";
local v = formatString % {a: "a"};
{
asd: v % {b: "1"}
}


上述代码无法编译通过,有没有办法实现在两个步骤中进行字符串插值?

使这变得棘手的一件事是格式字符串在开头是固定的,我不能仅仅依靠我已经有的参数来可靠地解析格式字符串。
英文:

Suppose I want to do:

local formatString = "Name: %(a)s Age: %(b)s";
local v = formatString % {a: "a"};
{
  asd: v % {b: "1"}
}

The above doesn't compile, is there any way to achieve this goal of doing string interpolation in two steps?

one thing that makes this tricky is that the format string is fixed at the beginning, I cannot realiably parse the format string with only the param I have

答案1

得分: 2

以下是翻译好的内容:

你可以通过 %% 转义第一个格式,就像下面的第一个示例一样。
或者(根据你的代码的上下文/复杂性),你可以通过将 b 作为格式化字符串本身传递来“欺骗”上面的片段,以满足所需字段的第一个要求,但保留结果字符串作为格式化字符串:

1) 通过 %% 转义第一个格式

local formatString = 'Name: %(a)s Age: %%(b)s';
local v = formatString % { a: 'a' };
{
  asd: v % { b: '1' },
}

2) 使用相同的格式化字符串

local formatString = 'Name: %(a)s Age: %(b)s';
local v = formatString % { a: 'a', b: '%(b)s' };
{
  asd: v % { b: '1' },
}

3) 使用变量进行“懒惰”(延迟)格式化

2) 相同,但有点通用:

local lazyEvalVar = 'someVar'; // 在上面的示例中为 `b`
local lazyEvalString = '%(someVar)s';

local formatString = 'Name: %(a)s Age: ' + lazyEvalString;
local v = formatString % { a: 'a', [lazyEvalVar]: lazyEvalString };
{
  asd: v % { [lazyEvalVar]: '1' },
}
英文:

You can escape the 1st formatting via %%, as in the 1st example below.
Alternatively (depending on the context/complexity of your code), you can "trick" the above snippet by passing b as a formatting string itself, so that you satisfy the 1st for required fields, but leave there ready the resulting string as a formatting one:

1) escape the 1st formatting via %%

local formatString = 'Name: %(a)s Age: %%(b)s';
local v = formatString % { a: 'a' };
{
  asd: v % { b: '1' },
}

2) using same formatting string

local formatString = 'Name: %(a)s Age: %(b)s';
local v = formatString % { a: 'a', b: '%(b)s' };
{
  asd: v % { b: '1' },
}

3) using a variable for "lazy" (late) formatting

Same as 2) but kinda generalized:

local lazyEvalVar = 'someVar'; // `b` in the above example
local lazyEvalString = '%(someVar)s';

local formatString = 'Name: %(a)s Age: ' + lazyEvalString;
local v = formatString % { a: 'a', [lazyEvalVar]: lazyEvalString };
{
  asd: v % { [lazyEvalVar]: '1' },
}

huangapple
  • 本文由 发表于 2023年6月9日 12:35:26
  • 转载请务必保留本文链接:https://go.coder-hub.com/76437239.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定