Django Template Variables and Javascript

后端 未结 15 2371
误落风尘
误落风尘 2020-11-22 05:59

When I render a page using the Django template renderer, I can pass in a dictionary variable containing various values to manipulate them in the page using {{ myVar }}

相关标签:
15条回答
  • 2020-11-22 06:30

    For a dictionary, you're best of encoding to JSON first. You can use simplejson.dumps() or if you want to convert from a data model in App Engine, you could use encode() from the GQLEncoder library.

    0 讨论(0)
  • 2020-11-22 06:30

    There are two things that worked for me inside Javascript:

    '{{context_variable|escapejs }}'
    

    and other: In views.py

    from json import dumps as jdumps
    
    def func(request):
        context={'message': jdumps('hello there')}
        return render(request,'index.html',context)
    

    and in the html:

    {{ message|safe }}
    
    0 讨论(0)
  • 2020-11-22 06:34

    I have found we can pass Django variables to javascript functions like this:-

    <button type="button" onclick="myJavascriptFunction('{{ my_django_variable }}')"></button>
    <script>
        myJavascriptFunction(djangoVariable){
           alert(djangoVariable);
        }
    </script>
    
    0 讨论(0)
提交回复
热议问题