【问题标题】:Erlang parse placeholder variablesErlang 解析占位符变量
【发布时间】:2019-03-16 11:26:13
【问题描述】:

我正在尝试创建一种特殊的模板格式,该格式必须定位 {{{--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("~p\n", [Result]).


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

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

干杯!

【问题讨论】:

    标签: erlang


    【解决方案1】:

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

    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

    【讨论】:

      猜你喜欢
      • 2018-08-14
      • 1970-01-01
      • 1970-01-01
      • 2022-11-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2015-03-11
      相关资源
      最近更新 更多