Created
July 30, 2012 04:12
-
-
Save SmileyChris/3204465 to your computer and use it in GitHub Desktop.
render tag
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 import template | |
from django.utils.safestring import mark_safe | |
import ttag | |
register = template.Library() | |
class Render(ttag.helpers.AsTag): | |
""" | |
A block tag that renders its contents to a context variable. | |
Here is an example of using it with a ``blocktrans`` tag:: | |
{% render as name %} | |
<a href="{{ profile.get_absolute_url }}">{{ profile }}</a> | |
{% endrender %} | |
{% blocktrans %}Logged in as {{ name }}{% endblocktrans %} | |
Here is an example of a simple base template that leverages this tag to | |
avoid duplication of a page title:: | |
{% render as title %} | |
{% block title %}The page title{% endblock %} | |
{% endrender %} | |
<html> | |
<head><title>{{ title }}</title></head> | |
<body> | |
<h1>{{ title }}</h1> | |
{% block body %}{% endblock %} | |
</body> | |
By default, the tag strips the output of leading and trailing white space. | |
To avoid this, use the ``no_strip`` argument:: | |
{% render no_strip as target %} ... {% endrender %} | |
""" | |
no_strip = ttag.BooleanArg() | |
class Meta(): | |
block = True | |
def as_value(self, data, context): | |
output = self.nodelist.render(context) | |
if 'no_strip' not in data: | |
output = output.strip() | |
return mark_safe(output) | |
register.tag(Render) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment