【问题标题】:How to convert a False or True boolean values inside nested python dictionary into javascript in Django template?如何将嵌套 python 字典中的 False 或 True 布尔值转换为 Django 模板中的 javascript?
【发布时间】:2022-11-30 14:40:01
【问题描述】:

这是我的观点.py

    context = {
        "fas": fas_obj,

    }

    # TemplateResponse can only be rendered once
    return render(request, "project_structure.html", context)

在 project_structure.html 和 javascript 部分

const pp = {{ fas|safe }};

我在这里得到一个错误。因为 fas 在内部某处包含一个 False 或 True 布尔值。 fas 很复杂并且有带有嵌套字典的字典列表。

有用的是我做了这个

    context = {
        "fas": fas_obj,
        # need a fas_json version for the javascript part 
        # because of the boolean in python doesn't render well in javascript
        "fas_json": json.dumps(fas_obj), 

我现在知道我有两个版本,因为我需要模板另一部分的原始版本

在javascript中

const pp = {{fas_json|safe}};

有没有比传递原始版本和 json 版本更简单的方法?

【问题讨论】:

    标签: javascript json django


    【解决方案1】:

    尝试这个:

    const pp = JSON.parse("{{fas_json|safe}}");
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-04-27
      • 1970-01-01
      • 2015-09-18
      • 2023-03-11
      • 1970-01-01
      • 1970-01-01
      • 2011-12-28
      • 1970-01-01
      相关资源
      最近更新 更多