def format_id(string): if string == 'anchor': return get_unique_id('anchor_') elif 'anchor' in string: return slugify(string) else: suffix = '_' if string else '' return get_unique_id('anchor_' + slugify(string) + suffix)
def unique_id_in_context(context): """Return an ID that is unique within the given context For a given request, return a unique ID each time this method is called. The goal is to generate IDs to uniquely identify elements in a template that are consistent between page loads. If the context has a request object, the generated id will increment: >>> context = {'request': request} >>> unique_id_in_context(context) # returns 1 >>> unique_id_in_context(context) # returns 2 >>> unique_id_in_context(context) # returns 3 If the context lacks a request, this function will return a 14-character unique alphanumeric string. """ request = context.get('request') if request: attribute_name = '__last_unique_id' if not hasattr(request, attribute_name): setattr(request, attribute_name, 0) id = getattr(request, attribute_name) + 1 setattr(request, attribute_name, id) return id else: return get_unique_id()