【问题标题】:Django html variable inside a json stringjson字符串中的Django html变量
【发布时间】:2019-07-17 06:37:30
【问题描述】:

我有一个包含变量的 json 字符串。

"country": {
    "name":"England",
    "city":"London",
    "description":"This country has a land mass of {{ info.1 }}km² and population is big as <span class=\"colorF88017\">{{ info.2 }} millions</span>.",
    "info":[
        null,
        [130395],
        [5479]
    ]
}

如您所见,这些变量链接到 json 文件中的列表。但是当我在模板 html 中这样做时:{{ country.description }} 它没有显示info.1 or info.2 包含的内容。它只是将所有内容显示为文本。

如何在字符串中显示变量的值?

from django.template.loader import render_to_string
def country_info(request):
    context = {}

    show = request.GET.get("show")
    if show:
        context["country"] = get_country_json()

    return render(request, 'country_info_index.html', context)

谢谢

【问题讨论】:

  • 这个 json 是在哪里创建的?它在视图文件中吗?
  • 没有从网站 api 获取 json
  • 如何在 api 中填充这个?在 api 中,您需要字符串联系,但您没有这样做。 {{ country.description }} 中的值将始终是 django 模板的纯文本
  • 对不起,我的意思是来自在线cdn中的json文件。我从后端读取 json 并将其呈现在前端。当然,它会显示描述,但不会填充 info.1 or info.2

标签: html json django


【解决方案1】:

使用render_to_string 传递如下参数

description_template.html:
This country has a land mass of { info.1 }km² and population is big as <span class=\"colorF88017\">{ info.2 } millions</span>.

在 render_to_string 中使用这个模板

from django.template.loader import render_to_string
template_name = "description_template.html"
description = render_to_string(template_name, 
  context={
     "info": description
  }
)

或使用 f 字符串

description =  f"This country has a land mass of { info.1 }km² and population is big as <span class=\"colorF88017\">{ info.2 } millions</span>."

【讨论】:

  • 我不太明白,你能解释一下吗?描述似乎也没有被使用。我也使用快捷方式render,它似乎使用render_to_string
  • @Printer 在传递给模板之前解析字符串。
  • @dan-klasson 我的电脑网络没了,所以我不能马上测试。但是我应该做一个模板过滤器并将描述作为值传递并将其作为render_to_string返回
  • @Printer 是的,就关注点分离而言,这将是更好的选择。但无论哪种方式都有效。
  • 干杯人,会试一试,希望它会奏效。只需要等待我的互联网恢复。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-05-27
  • 2012-09-30
  • 1970-01-01
相关资源
最近更新 更多