1

I have a json array and I want to pass this inside a javascript variable, inside the django template. I am able to access the variable inside django template {{variable}} . But not able to access this inside the javascript.This is my variable:

[
    
    {'Book ID': '1', 'Book Name': 'Challenging Times',
    
     'Category': 'Business', 'Price': '125.60'},
    
    {'Book ID': '2', 'Book Name': 'Learning JavaScript',
    
     'Category': 'Programming', 'Price': '56.00'}
    
]

I have used {{variable|safe}} inside the js but not working. Plz let me know where I am making the mistake.

1
  • Use json module of python and it's two methods json.loads() and json.dumps(), and also in JavaScript there a module JSON and it's two methods JSON.parse() and JSON.stringify(), to send and retrieve data in string datatype. Commented Feb 28, 2022 at 7:29

1 Answer 1

2

You should use the json_script template filter to add your variable to the template in a format that can be loaded in your JS

{{ variable|json_script:"foo" }}

<script>
    const foo = JSON.parse(document.getElementById('foo').textContent);
</script>
Sign up to request clarification or add additional context in comments.

4 Comments

This is not working
@Arun how is it not working, what error/issue are you getting?
I am not getting any error , the data what I am looking for is shown in the template via the js
@Arun it's not clear what your issue is, if you run console.log(foo) in your broswer's devtools console do you get the data you need?

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.