例如,如何在erlyDTL中使用巨大的json?

时间:2015-06-30 06:52:03

标签: erlang

我有 json

{
    "_total": 824,
    "_links": "self",
    "top": [
        {
            "viewers": 80896,
            "channels": 1177,
            "game": {
                "name": "League of Legends",
                "_id": 21779,
            }
        },
        {
            "viewers": 31211,
            "channels": 232,
            "game": {
                "name": "Dota 2",
                "_id": 29595,
            }
        }
    ]
}

如何最佳展示" top"清单?我试试:

Tuple = jsx:decode(unicode:characters_to_binary(Json)),
[_, _, Top] = Tuple,
Games = element(2, Top);

但是如何在模板中使用它?

{% for v in games %}
    {{ v.viewers }}<br><br>
    {{ v.channel }}<br><br>
    {{ v.game.name }}<br><br>
{% endfor %}

不起作用,然后显示{{games.game.name}}?

1 个答案:

答案 0 :(得分:1)

您所做的代码很好,只需要一些更新,您不应该将游戏传递给模板,而应该使用top作为键,例如,构建一个钢筋文件,如:

%rebar.config
{deps, [
    {erlydtl, ".*", {git, "git@github.com:erlydtl/erlydtl.git", "HEAD"}},
    {jsx, ".*", {git, "git@github.com:talentdeficit/jsx.git", "HEAD"}}
]}.

然后运行:

rebar get-deps
rebar compile

现在使用名为template.dtl的建议更新定义模板:

{% for v in top %}
    {{ v.viewers }}<br><br>
    {{ v.channels }}<br><br>
    {{ v.game.name }}<br><br>
{% endfor %}

启动erlang shell:

erl -pa ./deps/erlydtl/ebin/ -pa ./deps/merl/ebin/ -pa ./deps/jsx/ebin/

并执行应按预期显示模板的命令

Json = "{
    \"_total\": 824,
    \"_links\": \"self\",
    \"top\": [
        {
            \"viewers\": 80896,
            \"channels\": 1177,
            \"game\": {
                \"name\": \"League of Legends\",
                \"_id\": 21779,
            }
        },
        {
            \"viewers\": 31211,
            \"channels\": 232,
            \"game\": {
                \"name\": \"Dota 2\",
                \"_id\": 29595,
            }
        }
    ]
}".
Tuple = jsx:decode(unicode:characters_to_binary(Json)).
erlydtl:compile("./template.dtl", test).
test:render(Tuple).

给出了expecte输出

{ok,[[[<<"\n    ">>,"80896",<<"<br><br>\n    ">>,"1177",
   <<"<br><br>\n\t">>,<<"League of Legends">>,<<"<br><br>\n">>],
  [<<"\n    ">>,"31211",<<"<br><br>\n    ">>,"232",
   <<"<br><br>\n\t">>,<<"Dota 2">>,<<"<br><br>\n">>]],
 <<"\n">>]}

简而言之,在您的模板中,将games替换为top并将Tuple传递给模板