Reputation: 174
Please do not mark this question as invalid. I didn't find any question in stackoverflow with the problem mentioned below.
I have a django template. I pass the following context to it
context = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)
I have a HTML file where I have a dropdown. The dropdown have values like 1,2,3,4. I have registered a onClick function to it.
I need to achieve this functionality. I will get the value in onClick function. Then I will concatenate the received value with _title and store to it a javascript variable. Now I need to use that javascript variable to reference django context. I am not able to achieve this. I have googled and did extensive searching in stackoverflow. None seem to answer my question.
The javascript function looks like this:
function getContextValue(value) {
var key = value + '_title';
return {{ key }}
}
If I select 1 in the dropdown, then the above function will have key as 1_title. I need to return the 1_title value from context which is Title 1.
For me it doesn't work and returns 1_title only. I have even tried return {{ 'key' }} . In this it returns key.
Stackoverflow community please be kind. This may be a simple question for you but not for me.
Upvotes: 0
Views: 102
Reputation: 6839
If you wann access the context infos in JS you need to deliver it to JS somehow.
Change your context to something like this for easier access in the template.
context = {}
context['data_for_select'] = {
'1_title': 'Title 1',
'2_title': 'Title 2',
'3_title': 'Title 3',
'4_title': 'Title 4',
}
return render(request, 'index.html', context)
I assume you have something like this in the template:
<select name="dropdown">
{% for key, title in data_for_select.items %}
<option value="{{key}}">{{title}}</option>
{% endfor %}
</select>
You can now render the context data somewhere in the DOM for your JS method. Django provides a handy template filter called json_script https://docs.djangoproject.com/en/3.0/ref/templates/builtins/#json-script
{{ data_for_select|json_script:"select-data" }}
You can use it in JS like:
var data = JSON.parse(document.getElementById('select-data').textContent);
This way you have exposed your template context data to JS.
Upvotes: 1