nested inclusion tag that takes context

48 views
Skip to first unread message

Florian Auer

unread,
Nov 28, 2014, 7:46:54 AM11/28/14
to django...@googlegroups.com
Hi folks

I have written 2 simple inclusion tags where one is nested inside the other.
(settings.html uses the {% version %} tag)

Both ones refer to the request object inside the context.
The reason for this is, that I have a middleware that sets some flag variables to determine what type of client i'm serving.

code example:
@register.inclusion_tag('inclusion/settings.html', takes_context=True)
def settings(context):
    request
= context['request']
   
   
#needed for the template
   
return {'is_mobile:': request.is_mobile,
           
'is_tablet': request.is_tablet,
           
'is_phone': request.is_phone,
           
'user': request.user
   
}
@register.inclusion_tag('inclusion/version.html', takes_context=True)
def version(context):
    request
= context['request']
   
    version_nr
= '0.0.0'
    version_date
= '01.01.1970'
    f
= open(os.path.join(BASE_DIR, 'version.txt'), 'r')
   
for line in f:
        token
= line.split(':')
       
if token[0] == 'version':
            version_nr
= token[1]
       
elif token[0] == 'datum':
            version_date
= token[1]
    f
.close()

   
return {'is_mobile:': request.is_mobile,
           
'is_tablet': request.is_tablet,
           
'is_phone': request.is_phone,
           
'version_nr': version_nr,
           
'version_date': version_date
   
}

If i now user the {% version %} tag inside the settings.html th system complains that context['request'] is not defined for the version() function.
It seems I can fix this by putting the request object into the return object of the settings funktion like:
@register.inclusion_tag('inclusion/settings.html', takes_context=True)
def settings(context):
    request
= context['request']
   
   
return {'request': request,
           
'is_mobile:': request.is_mobile,
           
'is_tablet': request.is_tablet,
           
'is_phone': request.is_phone,
           
'user': request.user
   
}
But is this the correct way?


Also interesting is:
If I leave out the addiotion sending the request insite the result of settings back, the context object inside the version function seems to have an unnamed property at the second index that may to be some kind of request object.
[{'None': None, 'True': True, 'False': False}, 
 
{'is_mobile:': True, 'user': <SimpleLazyObject: <User: test>>, 'is_phone': False, 'csrf_token': <django.utils.functional.lazy.<locals>.__proxy__ object at 0x00000000054A7828>, 'is_tablet': True}
]




Reply all
Reply to author
Forward
0 new messages