Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Determining if I need quotes in HTML with django template

I have a dict in python that is something like the following:

d = {'key1': .98, 'key2': 'some_str', 
     #...
    }

In this dictionary some keys will be mapped to float and others will be mapped to str

In my HTML I am doing something like the following:

html_dict = {
{% for k, v in my_dict.items %}
     {{ k }}: "{{ v }}",
{% endfor %}
};

However this approach wraps the floats in quotes as well, which is what I don't want. But if I don't know wrap them in quotes the HTML doesn't understand that they are are string values. I would ideally like something like the following:

html_dict = {
{% for k, v in my_dict.items %}
     {% if check_v_is_str %}
         {{ k }}: "{{ v }}",
     {% else %}
         {{ k }}: {{ v }},
     {% endif %}
{% endfor %}
};
like image 573
sedavidw Avatar asked Dec 02 '25 22:12

sedavidw


1 Answers

Don't do this. You are manually trying to replicate a JS data structure, when there already exists a well-defined structure that both Python and JS know about, namely JSON. Use that instead. Convert the dict to JSON in your view, and pass it to the template where it can be output directly.

like image 103
Daniel Roseman Avatar answered Dec 05 '25 13:12

Daniel Roseman



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!