最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

Accessing Django template {{Variable}} from JavaScript - Stack Overflow

programmeradmin1浏览0评论

I tried to access django template variable in html page inline javascript, it works fine. But if I include js using <script src="..> then it dont work. Is this limitation or I'm doing something wrong? I really appreciate your help.

I tried to access django template variable in html page inline javascript, it works fine. But if I include js using <script src="..> then it dont work. Is this limitation or I'm doing something wrong? I really appreciate your help.

Share Improve this question asked Jul 27, 2010 at 3:33 DipakDipak 4436 silver badges17 bronze badges
Add a comment  | 

2 Answers 2

Reset to default 12

The included Javascript isn't processed by the Django template processor on the server, so that won't work. If you need to pass information through the template to included Javascript files, have your template create a small <script> block wherein some global variable is declared to contain those template variables. Then, your pure Javascript file can get the values by looking for the global object created by that <script> from the template.

Pointy's answer is correct. I often find this filter useful for that situation:

@register.filter(name='json')
def _json(obj):
  #remember to make sure the contents are actually safe before you use this filter!
  return safestring.mark_safe(json.dumps(obj)) 

then in a <script> tag I can just do something like this:

window.g_details = {{ details|json }};
发布评论

评论列表(0)

  1. 暂无评论