Q:

Search through context in custom templatetag

I am currently in the process of reducing my template code by using custom templatetags. I am essentially passing the context from the view to the tag and then rendering that into a shared template. I have come up against a problem that I have been unable to solve, however.
The context of the views I am passing to the tag each contain a key which ends in '_collection'. Essentially, I need to go through the context and find the key/value pair that corresponds to that substring and then map it to the tag context.
Here is the templatetag I am using:
from django import template

register = template.Library()

@register.inclusion_tag('main/collection.html', takes_context=True)
def collection(context):
    ctx = {
        'is_create': context['is_create']
    }

    if '_collection' in context:
        # not sure how to get this into the context

    return ctx

Basically I just want to correctly map that value to the templatetag context by using that substring.
Any help would be much appreciated.
Thanks for your time.

A:

If I understood your question correctly, all you want is to create a mapping from the context by only taking certain keys (those which end with "_context")
ctx = {
    key.split("_collection")[0]: value
    for key, value in context.flatten().items()
    if key.endswith("_collection")
}

This should be enough. Note the split on key. It will change foo_collection to foo. If this is not wanted, you can just use the key directly without the split.
Calling flatten() on the context is supposed to return a dict combining the context data from all sources (view & all context preprocessors). Since we now have a dict, we can iterate over it's items without any issues.
You can then add any specific keys you want to add
ctx['is_create'] = context['is_create']

Alternatively if you don't want to call flatten you can iterate over the context and do something like 
ctx = {
    'is_create': context['is_create']
}
for key in context:
   if key.endswith("_collection"):
       ctx[key.split("_collection")[0]] = context[key]

