0

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.

1
  • I added an generic answer how to expose template context data to JS. I'm not sure though if this is what you are asking for. Anyway I hope it points you in the right direction. Commented Feb 14, 2020 at 13:15

1 Answer 1

1

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.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.