Skip to content

Instantly share code, notes, and snippets.

@SmileyChris
Created July 30, 2012 04:12

Revisions

  1. SmileyChris revised this gist Jul 30, 2012. 1 changed file with 5 additions and 9 deletions.
    14 changes: 5 additions & 9 deletions render_tag.py
    Original file line number Diff line number Diff line change
    @@ -23,16 +23,12 @@ class Render(ttag.helpers.AsTag):
    {% block title %}The page title{% endblock %}
    {% endrender %}
    <html>
    <head><title>{{ title }}</title></head>
    <body><h1>{{ title }}</h1></body>
    {% render as target_user %}
    {% with user=friend %}{{ pretty_user }}{% endwith %}
    {% endrender %}
    {% blocktrans %}
    {{ current_user }} connected with {{ target_user }}
    {% endblocktrans %}
    <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::
  2. SmileyChris created this gist Jul 30, 2012.
    54 changes: 54 additions & 0 deletions render_tag.py
    Original file line number Diff line number Diff line change
    @@ -0,0 +1,54 @@
    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 %}
    <head><title>{{ title }}</title></head>
    <body><h1>{{ title }}</h1></body>
    {% render as target_user %}
    {% with user=friend %}{{ pretty_user }}{% endwith %}
    {% endrender %}
    {% blocktrans %}
    {{ current_user }} connected with {{ target_user }}
    {% endblocktrans %}
    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)