enchance
enchance

Reputation: 30411

How to get template variable from within a custom template tag

In Django, is there a way for a custom template tag to have access to the current template's variables passed on by the view?

My first thought is to make a parameter where the user can place the template variable manually but if my custom template tag can access the variable itself then it would be much better!

To illustrate, I want to get rid of the parameter templatevar

@register.simple_tag
def sampletag(templatevar):
    return templatevar

Upvotes: 0

Views: 130

Answers (1)

Daniel Roseman
Daniel Roseman

Reputation: 599520

You can use the takes_context parameter to the decorator.

@register.simple_tag(takes_context=True)
def sampletag(context):
    return context['templatevar']

See the template tags documentation.

Upvotes: 2

Related Questions