Created
January 21, 2024 15:53
-
-
Save matiboy/c0e22ccc2baa53b2045fa867720dd1ab to your computer and use it in GitHub Desktop.
Django template tag setting variable to context with an if/else condition
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| from django.template.defaulttags import TemplateIfParser | |
| from django import template | |
| register = template.Library() | |
| class IfElseAs(template.Node): | |
| def __init__(self, condition, if_var, else_var, var_name): | |
| self.condition = condition | |
| self.if_var = template.Variable(if_var) | |
| self.else_var = template.Variable(else_var) | |
| self.var_name = var_name | |
| def render(self, context): | |
| context[self.var_name] = (self.if_var if self.condition.eval(context) else self.else_var).resolve(context) | |
| return "" | |
| @register.tag | |
| def if_else_as(parser, token): | |
| """ Usage: | |
| {% if_else_as condition then if_var else else_var as var_name %} | |
| where | |
| condition: a multi part condition separated by spaces; this uses the same evaluation as Django's own `{% if` tag | |
| if_var: the value or variable name used when condition is true | |
| else_var: the value or variable name used when condition is false | |
| var_name: the name of the variable added to/set in the template context | |
| Other parts of the template tags (then/else/as) are only there for readability | |
| e.g. | |
| {% if_else_as author == "Douglas Adams" then 42 else a_context_var as answer_to_universe %} | |
| {{answer_to_universe}} # outputs 42 assuming the context variable `author` is "Douglas Adams" | |
| """ | |
| parts = token.split_contents() | |
| _tag_name, *expressions, _then, if_var, _else, else_var, _as, var_name = parts | |
| condition = TemplateIfParser(parser, expressions).parse() | |
| return IfElseAs(condition, if_var, else_var, var_name) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment