Printer
Printer

Reputation: 465

Django html variable inside a json string

I have a json string that contains a variable.

"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]
    ]
}

As you see those variables are linked to a list in the json file. But when i do in the template html: {{ country.description }} It does not show what info.1 or info.2 contains. It just display everything as a text.

How can i display the value from a variable inside a string?

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)

Thanks

Upvotes: 1

Views: 245

Answers (1)

Hari
Hari

Reputation: 1623

Use render_to_string pass the arguments like 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>.

use this template in 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
  }
)

or using f string

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

Upvotes: 2

Related Questions