如何在javascript中引用django变量?

时间:2010-09-28 22:13:24

标签: django django-templates

我正在开发一个项目,要求我使用view.py模板中变量中包含的值。我需要在我的javascript中使用该变量。有没有人知道将变量从django传递给JS的正确方法?

这是我在views.py中的功能

@login_required
@never_cache_headers
def user_feed(request, user=None, extension=None):
# Ensure we have a user
if user is None:
    user = request.user
    prof = user.get_profile()
elif isinstance(user, basestring):
    user = get_object_or_404(User, id=user)

# Build author list
author_ids = []
author_ids.append(user.id)

# Check if user if friend to profile being viewed
are_friends = Friendship.objects.are_friends(user, request.user)

# Determine Date
now = datetime.datetime.now()
today = now.date()
if now.time() < datetime.time(3):
    start_dt = datetime.datetime.now() - datetime.timedelta(hours=settings.FEEDITEM_BUFFER_HOURS)
else:
    start_dt = datetime.datetime(today.year, today.month, today.day)

# Build up the where query
where = [] 
if user.id != request.user.id:
    where.append({'ping_type':'public'})
    if are_friends: 
        where.append({'ping_type': 'friends_only'})
        where.append({'ping_type': 'invite_only', 'invite_list': request.user.id})
    where = {'$or': where}
else: where = {} # Vanity check - show all pings by author

where['author'] = { '$in' : author_ids }
where['starts'] = { "$gt":start_dt }
where['deleted'] = { "$ne": True }
# print "User View Where = ", where

feeditems, has_more = ds.Feed.feeditems(request, where)

feeditems = ds.FeedItem.prepare(feeditems)
friend_requested = FriendshipInvitation.objects.is_friend_requested(request.user, user)

if extension:
  if extension == 'json':
    return http.HttpResponse(json.dumps(feeditems, indent=2, default=json_handler),
                        mimetype='application/json')
else:
  return render_to_response("social/feeditems_list.html", {
    'feeditems':feeditems,
    'user':user,
    'has_more':has_more,
    'section':'user_feed',
    'are_friends':are_friends,
    'friend_requested':friend_requested,
}, request)

我基本上需要将request.user.id或user.id传递给Javascript。

修改

实际上,我宁愿将它作为自己的小元素json数组传递给javascript,如果可能的话

1 个答案:

答案 0 :(得分:5)

也许有点明显,但是怎么样:

<script type="text/javascript">
    var userId = {{ user.id|default:null }};
</script>