Created
December 9, 2021 12:55
-
-
Save cuu508/a221a66519c32b3810997644000baac9 to your computer and use it in GitHub Desktop.
Experimental {% linemode %} and {% line %} template tags
This file contains 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
class LineModeNode(Node): | |
def __init__(self, nodelist): | |
self.nodelist = nodelist | |
def render(self, context): | |
context["__lines__"] = [] | |
self.nodelist.render(context) | |
return "\n".join(context["__lines__"]) | |
@register.tag | |
def linemode(parser, token): | |
""" Trim whitespace and newlines outside {% line %} blocks. | |
Example usage:: | |
{% linemode %} | |
{% line %}Line one.{% endline %} | |
This content will be ignored. | |
{% if True %} | |
{% line %}Line two.{% endline %} | |
{% endif %} | |
{% endlinemode %} | |
This example returns this text:: | |
Line one. | |
Line two. | |
""" | |
nodelist = parser.parse(("endlinemode",)) | |
parser.delete_first_token() | |
return LineModeNode(nodelist) | |
class LineNode(Node): | |
def __init__(self, nodelist): | |
self.nodelist = nodelist | |
def render(self, context): | |
context["__lines__"].append(self.nodelist.render(context)) | |
return "" | |
@register.tag | |
def line(parser, token): | |
""" For use with {% linemode %}. | |
Renders the enclosed content and appends it to context["__lines__"], | |
instead of returning it. | |
""" | |
nodelist = parser.parse(("endline",)) | |
parser.delete_first_token() | |
return LineNode(nodelist) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment