1

My web app contains a banner serving API.

Abridged banner model:

class Banner(models.Model):
    name = models.CharField(max_length=50)
    ad_tag = models.TextField()
    active = models.BooleanField(default=True)
    priority = models.IntegerField(null=True, blank=False)

    def __unicode__(self):
        return self.name

The banner serving API accepts some GET parameters and, based on these parameters, returns a Django template that spits out the ad_tag TextField above. The ad_tag field is the banner's HTML:

<!-- ... -->
<body>
    {{ ad_tag|safe}}
</body>

My problem: I would like to process the contents of the ad_tag field with the Django template processor, so I can use includes, template logic, etc. Is this possible?

bfox
  • 274
  • 2
  • 13
  • 1
    you would probably need to write a templatetag ... but it might be something others are interested in (so you might wanna throw it up on github or something) – Joran Beasley May 06 '15 at 00:04
  • @JoranBeasley That sounds interesting, thanks. Any ideas how a template tag could be made to invoke the template processor on the contents of `ad_tag`? – bfox May 06 '15 at 00:42

1 Answers1

1

I had success with the following snippet by GitHub user mhulse. This allowed me to call {% allow_tags ad_tag %} in my template and process any Django template tags found in that field.

from django import template
from django.utils.safestring import mark_safe

register = template.Library()

# https://surdu.me/2011/02/18/set-variable-django-template.html
# http://djangosnippets.org/snippets/861/
# http://stackoverflow.com/questions/4183252/what-django-resolve-variable-do-template-variable
# https://docs.djangoproject.com/en/dev/ref/templates/api/

@register.tag
def allow_tags(parser, token):

    """
    Example: {% allow_tags page.content %}
    """

    try:
        # Splitting by None == splitting by spaces:
        tag_name, var_name = token.contents.split(None, 1)
    except ValueError:
        raise template.TemplateSyntaxError, '%r tag requires arguments' % token.contents.split()[0]

    return RenderNode(var_name)
allow_tags.is_safe = True

class RenderNode(template.Node):

    def __init__(self, content):
        self.content = content

    def render(self, context):
        try:
            content = template.Variable(self.content).resolve(context)
            return template.Template(content).render(template.Context(context, autoescape=False))
        except template.TemplateSyntaxError, e:
            return mark_safe('Template error: There is an error one of this page\'s template tags: <code>%s</code>' % e.message)
Nicu Surdu
  • 8,172
  • 9
  • 68
  • 108
bfox
  • 274
  • 2
  • 13