I have a partial template that needs a random string every time its included. I need access the same random string than once per include and I’m not sure how many times the partial will be included.
I’m currently doing this to add it to the context
@register.tag
def randomgen(parser, token):
return RandomgenNode()
class RandomgenNode(template.Node):
def render(self, context):
context['randomgen_str'] = os.urandom(16).encode('hex')
return ''
This lets me do {% randomgen %} at the beginning of the partial and {{ randomgen_str }} where I need the string. This isn’t necessarily bad, I just didn’t know if there was a preferred way to accomplish this.
Thanks
Thanks to garromark’s I was able to find the best solution. Assignment tag did exactly what I wanted.
Then in my template I could use the following at the to of my included template
and use the following where I needed the random string