【问题标题】:How to render template with python json as treeview?如何使用 python json 渲染模板作为树视图?
【发布时间】:2019-03-25 19:54:00
【问题描述】:

我需要用烧瓶渲染一个 html 模板。 我在 python 中有一个字典,我想在树视图中显示它。 我该怎么做?

我找到了这个资源:https://github.com/jonmiles/bootstrap-treeview 这可能有用,但我不能使用它。

dict_var = {
    "test3@test3.com": {
        "discord_id": 0,
        "status_key": False,
        "username": "test3@test3.com",
        "last_name": "aaaa",
        "gender": "male",
        "email": "test3@test3.com",
    },
    "test9@test9.com": {
        "username": "test9@test9.com",
        "last_name": "test9",
        "gender": "male",
        "discord_data": {
            "user": {
                "avatar": None,
                "discriminator": "111",
                "verified": True,
            },
            "connections": [],
            "guilds": [
                {
                    "icon": "hellohellohellohello.jpg",
                    "id": "222222222222",
                },
                {
                    "icon": None,
                    "id": "111111111",
                    "owner": True,
                }
            },
            "email": "hello@hello.com",
            "activation_key": "hello-hello-hello-hello-hello",
            "first_name": "hello@hello.com",
            "discord_id": 22222223333334444,
            "state": "IT"
        }
    }

渲染模板的flask函数

@app.route('/test')
def test():
   return render_template('test.html', res=dict_var)


test.html

...

<div class="container">
    <div id="tree"></div>

<script>
    $(function() {
  var mytree = JSON.parse('{{ res|safe }}');

  $('#tree').treeview({
    data: mytree
  });
});
</script>


...

如何将res传递给js并将dict转换为treeview?

【问题讨论】:

  • 您的 json_var 不是 JSON,而是 Python 字典。 (它可以很容易地转换为 JSON 和从 JSON 转换,但您可能不需要这样做,特别是如果您已经将它作为模板变量传递。)至于在模板中放入什么,这一切都取决于什么您试图从该词典中显示的信息,以及如何显示 - 您真的没有明确说明您想要什么。
  • 是的,我错了。我编辑代码。现在问题出在哪里? @RobinZigmond
  • 我不熟悉“treeview” - 但我注意到的一件事是,由于您在res 上调用JSON.parse,它实际上需要be JSON。为此,您需要将其作为json.dumps(dict_var) 传递给模板。
  • @RobinZigmond 它不起作用。但不要引发错误
  • 好吧,“它不起作用”不是很有帮助 - 我真的不知道你想做什么。 (正如我所说,我以前从未遇到过这种“树视图”。)但是,快速浏览一下文档,似乎说数据需要是一个数组,而你的是一个对象。

标签: javascript python python-3.x flask jinja2


【解决方案1】:

您可以使用tojson

...


<div class="container">
    <div id="tree"></div>

<script>
    $(function() {
  var mytree = JSON.parse('{{ res|tojson }}');

  $('#tree').treeview({
    data: mytree
  });
});
</script>


...

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-12-27
    • 2023-03-19
    • 1970-01-01
    • 2012-07-27
    • 1970-01-01
    相关资源
    最近更新 更多