Erlang 解析占位符变量



我正在尝试创建一种特殊的模板格式,该格式必须定位{{{--example_id--}}}的出现并单独替换该内容,并通过括号括起来的值获取它。

我最初的尝试是分开我的方式,我在下面发布了一些示例代码,这些代码尚未针对多个占位符进行优化,并且一次只能处理一个占位符。

parse_text() ->
Text = <<"this is text {{{--test_placeholder_1--}}} and this also">>,
% would not work here:
% Text = <<"this is text {{{--test_placeholder_1--}}} and this {{{--test_placeholder_2--}}} also">>,
[_,Tail] = binary:split(Text, [<<"{{{--">>],[global]),
[Id|_] = binary:split(Tail, [<<"--}}}">>],[global]),
Pattern = <<"{{{--", Id/binary, "--}}}">>,
Replacement = get_content(Id),
Result = binary:replace(Text, Pattern, Replacement),
io:fwrite("~pn", [Result]).

get_content(<<"test_placeholder_1">>)->
<<"test id 1!">>;
get_content(<<"test_placeholder_2">>)->
<<"test id 2!">>;
get_content(_)->
<<"not found text!">>.

我的问题是,我应该进一步优化它以支持一个文本中的多个占位符,还是有更好的方法来处理这样的问题?

干杯!

我不确定这是更好的主意,但它适用于多个占位符

parse_text(Input) ->
List = lists:foldr(
fun(E, Acc) ->
case get_content(E) of
<<"not found text!">> -> [E| Acc];
Match -> [Match | Acc]
end 
end, [], binary:split(Input, [<<"{{{--">>, <<"--}}}">>], [global])
),
erlang:list_to_binary(List).

get_content(<<"test_placeholder_1">>)->
<<"test id 1!">>;
get_content(<<"test_placeholder_2">>)->
<<"test id 2!">>;
get_content(_)->
<<"not found text!">>.

如果您需要更强大的工具来执行此类任务

我觉得你应该检查一下 ErlyDTL 插件 -- ErlyDTL Wiki

最新更新