我有一个包含变量的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)
谢谢
答案 0 :(得分:2)
使用render_to_string
传递诸如follow之类的参数
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>."