Example #1
0
def static_content(content, render_mode):
    if render_mode == 'markdown':
        return mark_safe(markdown.markdown(unicode(content), ["settingsparser"]))
    elif render_mode == "html":
        return mark_safe(unicode(content))
    else:
        return unicode(content)
Example #2
0
 def as_text(self):
     """
     Dialog Forms rendered as summary just display their values instead of input fields.
     This is useful to render a summary of a previously filled out form.
     """
     try:
         return mark_safe(self.instance.as_text())
     except (AttributeError, TypeError):
         output = []
         for name in self.fields.keys():
             bound_field = self[name]
             value = bound_field.value()
             if bound_field.is_hidden:
                 continue
             if isinstance(value, (list, tuple)):
                 line = []
                 cast_to = type(tuple(bound_field.field.choices)[0][0])
                 for v in value:
                     try:
                         line.append(dict(bound_field.field.choices)[cast_to(v)])
                     except (AttributeError, KeyError):
                         pass
                 output.append(force_text(', '.join(line)))
             elif value:
                 try:
                     value = dict(bound_field.field.choices)[value]
                 except (AttributeError, KeyError):
                     pass
                 output.append(force_text(value))
         return mark_safe('\n'.join(output))
Example #3
0
 def get_page_number(self, i):
     if i == DOT:
         return mark_safe(u'<span class="dot-page">...</span> ')
     elif i == self.page_num:
         return mark_safe(u'<span class="this-page">%d</span> ' % (i + 1))
     else:
         return mark_safe(u'<a href="%s"%s>%d</a> ' % (escape(self.get_query_string({PAGE_VAR: i})), (i == self.paginator.num_pages - 1 and ' class="end"' or ''), i + 1))
Example #4
0
def group_message_details(request, group_id, message_id):
    group = get_object_or_404(GroupedMessage, pk=group_id)

    message = get_object_or_404(group.message_set, pk=message_id)
    
    if '__sentry__' in message.data and 'exc' in message.data['__sentry__']:
        module, args, frames = message.data['__sentry__']['exc']
        message.class_name = str(message.class_name)
        # We fake the exception class due to many issues with imports/builtins/etc
        exc_type = type(message.class_name, (Exception,), {})
        exc_value = exc_type(message.message)

        exc_value.args = args
    
        reporter = ImprovedExceptionReporter(message.request, exc_type, exc_value, frames, message.data['__sentry__'].get('template'))
        traceback = mark_safe(reporter.get_traceback_html())
    elif group.traceback:
        traceback = mark_safe('<pre>%s</pre>' % (group.traceback,))
    
    def iter_data(obj):
        for k, v in obj.data.iteritems():
            if k.startswith('_') or k in ['url']:
                continue
            yield k, v

    json_data = iter_data(message)

    page = 'messages'

    return render_to_response('sentry/group/message.html', locals(),
                              context_instance=RequestContext(request))
Example #5
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)
        if value:
            objs = lookup.get_objects([value])
            try:
                obj = objs[0]
            except IndexError:
                raise Exception("%s cannot find object:%s" % (lookup, value))
            display = lookup.format_item_display(obj)
            current_repr = mark_safe( """new Array("%s",%s)""" % (escapejs(display),obj.pk) )
        else:
            current_repr = 'null'

        context = {
                'name': name,
                'html_id' : self.html_id,
                'min_length': getattr(lookup, 'min_length', 1),
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_repr': current_repr,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                }
        context.update(bootstrap())
        
        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #6
0
def embedly(url, size='640x480'):
    """ A very minimalistic implementation of embedly oembed content """

    size_match = re.match(r'^(?P<width>\d+)x(?P<height>\d+)$', size)

    if not size_match:
        raise Exception('Could not parse size, should be <width>x<height>')

    maxsizes = size_match.groupdict()

    params = {
        'url': url,
        'maxwidth': maxsizes['width'],
        'maxheight': maxsizes['height']
    }

    embedly_url = 'http://api.embed.ly/1/oembed?%s' % urlencode(params)
    cache_key = 'embedly_%s' % sha1(embedly_url).hexdigest()

    result = cache.get(cache_key)

    if not result:
        try:
            request = urllib2.urlopen(embedly_url)
            response = request.read()
            data = json.loads(response)
            result = mark_safe(data['html'])
            cache.set(cache_key, result)
        except urllib2.URLError:
            return mark_safe('<p>External content could not be loaded...</p>')

    return result
Example #7
0
    def form_valid(self, form):
        ticketed_event = form.save()
        messages.success(
            self.request, mark_safe('Event <strong> {}</strong> has been '
                                    'created!'.format(ticketed_event.name))
        )
        ActivityLog.objects.create(
            log='Ticketed Event {} (id {}) created by admin user {}'.format(
                ticketed_event, ticketed_event.id, self.request.user.username
            )
        )

        if ticketed_event.paypal_email != settings.DEFAULT_PAYPAL_EMAIL:
            messages.warning(
                self.request,
                mark_safe(
                    "You have changed the paypal receiver email from the "
                    "default value. If you haven't used this email before, "
                    "it is strongly recommended that you test the email "
                    "address "
                    "<a href='/studioadmin/test-paypal-email?email={}'>"
                    "here</a>".format(ticketed_event.paypal_email)
                )
            )

        return HttpResponseRedirect(self.get_success_url())
Example #8
0
def get_image_tags_per_issue(issue, alt_text, zoom_level, as_list=False,
                             variants=False, exclude_ids=None):
    if issue.has_covers() or (variants and issue.variant_covers().count()):
        covers = issue.active_covers()
        if variants:
            covers = covers | issue.variant_covers()
    else:
        return mark_safe(get_image_tag(cover=None, zoom_level=zoom_level,
                    alt_text=alt_text,
                    can_have_cover=issue.can_have_cover()))

    if exclude_ids:
        covers = covers.exclude(id__in=exclude_ids)
    if as_list:
        cover_tags = []
        alt_string = u'Cover for %s' % issue.full_name()
    else:
        tag = ''

    for cover in covers:
        if as_list:
            active = cover.revisions.filter(changeset__state__in=states.ACTIVE)
            cover_tags.append([cover, issue,
                               get_image_tag(cover, alt_string, zoom_level),
                               active.count()])
        else:
            tag += get_image_tag(cover=cover, zoom_level=zoom_level,
                                 alt_text=alt_text)
    if as_list:
        return cover_tags
    else:
        return mark_safe(tag)
Example #9
0
    def test_mark_safe_lazy(self):
        s = lazystr('a&b')
        b = lazybytes(b'a&b')

        self.assertIsInstance(mark_safe(s), SafeData)
        self.assertIsInstance(mark_safe(b), SafeData)
        self.assertRenderEqual('{{ s }}', 'a&b', s=mark_safe(s))
Example #10
0
    def render_buglinks(self, record, table=None):

        suite_links_count = BugLink.objects.filter(
            content_type=ContentType.objects.get_for_model(TestSuite),
            object_id=record.id).count()
        case_links_count = BugLink.objects.filter(
            content_type=ContentType.objects.get_for_model(TestCase),
            object_id__in=TestCase.objects.filter(
                suite=record)).count()

        user = table.context.get('request').user
        if not user.is_anonymous():
            return mark_safe(
                '<a href="#" class="buglink" id="buglink_%s">[%s]</a> (%s)' % (
                    record.id,
                    suite_links_count,
                    case_links_count
                )
            )
        else:
            return mark_safe(
                '[%s] (%s)' % (
                    suite_links_count,
                    case_links_count
                )
            )
Example #11
0
def paginator_number(cl,i):
    if i == DOT:
        return u'... '
    elif i == cl.page_num:
        return mark_safe(u'<span class="this-page">%d</span> ' % (i+1))
    else:
        return mark_safe(u'<a href="%s"%s>%d</a> ' % (cl.get_query_string({PAGE_VAR: i}), (i == cl.paginator.num_pages-1 and ' class="end"' or ''), i+1))
Example #12
0
    def get(self, request, *args, **kwargs):

        if not self.has_permission(request):
            return self.handle_permission_denied(request)

        template_name = rfs.SWAGGER_SETTINGS.get('template_path')
        data = {
            'swagger_settings': {
                'discovery_url': "%s/api-docs/" % get_full_base_path(request),
                'api_key': rfs.SWAGGER_SETTINGS.get('api_key', ''),
                'api_version': rfs.SWAGGER_SETTINGS.get('api_version', ''),
                'token_type': rfs.SWAGGER_SETTINGS.get('token_type'),
                'enabled_methods': mark_safe(
                    json.dumps(rfs.SWAGGER_SETTINGS.get('enabled_methods'))),
                'doc_expansion': rfs.SWAGGER_SETTINGS.get('doc_expansion', ''),
            },
            'rest_framework_settings': {
                'DEFAULT_VERSIONING_CLASS':
                    settings.REST_FRAMEWORK.get('DEFAULT_VERSIONING_CLASS', '')
                    if hasattr(settings, 'REST_FRAMEWORK') else None,

            },
            'django_settings': {
                'CSRF_COOKIE_NAME': mark_safe(
                    json.dumps(getattr(settings, 'CSRF_COOKIE_NAME', 'csrftoken'))),
            }
        }
        response = render_to_response(
            template_name, RequestContext(request, data))

        return response
Example #13
0
    def render(self, name, value, attrs=None):

        value = value or ''
        final_attrs = self.build_attrs(attrs,  name=name)
        self.html_id = final_attrs.pop('pk', name)

        lookup = get_lookup(self.channel)
        if value:
            current_result = mark_safe(lookup.format_result( lookup.get_objects([value])[0] ))
        else:
            current_result = ''

        context = {
                'name': name,
                'html_id' : self.html_id,
                'lookup_url': reverse('ajax_lookup',kwargs={'channel':self.channel}),
                'current_id': value,
                'current_result': current_result,
                'help_text': self.help_text,
                'extra_attrs': mark_safe(flatatt(final_attrs)),
                'func_slug': self.html_id.replace("-",""),
                'add_link' : self.add_link,
                'admin_media_prefix' : settings.ADMIN_MEDIA_PREFIX
                }

        return mark_safe(render_to_string(('autocompleteselect_%s.html' % self.channel, 'autocompleteselect.html'),context))
Example #14
0
    def prepare(self):
        # Set the template and title for the page content, if they are not set (but don't save them)
        self.title = self.title or self.page.title
        self.template = self.template or self.page.template
        self.slug = self.slug or self.page.slug

        if not self.description:
            self.description = ''
        if not self.keywords:
            self.keywords = ''
        if not self.page_topic:
            self.page_topic = ''
    
        # Convert the content to HTML
        if self.content_type == 'html':
            pass # Nothing to do
        elif self.content_type == 'markdown':
            self.content = markdown(self.content)
        elif self.content_type == 'textile':
            self.content = textile(self.content)
        elif self.content_type == 'rst':
            self.content = rst(self.content)
        else:
            self.content = mark_safe(linebreaks(escape(self.content)))
        self.toc = mark_safe(self.toc)
        return self
def format_value(value):
    if getattr(value, 'is_hyperlink', False):
        name = six.text_type(value.obj)
        return mark_safe('<a href=%s>%s</a>' % (value, escape(name)))
    if value is None or isinstance(value, bool):
        return mark_safe('<code>%s</code>' % {True: 'true', False: 'false', None: 'null'}[value])
    elif isinstance(value, list):
        if any([isinstance(item, (list, dict)) for item in value]):
            template = loader.get_template('rest_framework/admin/list_value.html')
        else:
            template = loader.get_template('rest_framework/admin/simple_list_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, dict):
        template = loader.get_template('rest_framework/admin/dict_value.html')
        context = {'value': value}
        return template.render(context)
    elif isinstance(value, six.string_types):
        if (
            (value.startswith('http:') or value.startswith('https:')) and not
            re.search(r'\s', value)
        ):
            return mark_safe('<a href="{value}">{value}</a>'.format(value=escape(value)))
        elif '@' in value and not re.search(r'\s', value):
            return mark_safe('<a href="mailto:{value}">{value}</a>'.format(value=escape(value)))
        elif '\n' in value:
            return mark_safe('<pre>%s</pre>' % escape(value))
    return six.text_type(value)
Example #16
0
def project_div(project):
    d = dict(name=esc(project.name), color=esc(project.color))
    if project.display_as_free:
        return mark_safe('<div class="project %(color)s"></div>' % d)
    else:
        d['url'] = project.get_absolute_url()
        return mark_safe('<a href="%(url)s" class="project %(color)s" title="%(name)s"></a>' % d)
Example #17
0
def chain_recursion(r_id, store, id_dict):
    """Helper function for recusion"""
    
    i = pki.models.CertificateAuthority.objects.get(pk=r_id)
    
    div_content = build_delete_item(i)
    store.append( mark_safe('Certificate Authority: <a href="%s">%s</a> <img src="%spki/img/plus.png" class="switch" /><div class="details">%s</div>' % \
                            (urlresolvers.reverse('admin:pki_certificateauthority_change', args=(i.pk,)), i.name, MEDIA_URL, div_content)) )
    
    id_dict['ca'].append(i.pk)
    
    ## Search for child certificates
    child_certs = pki.models.Certificate.objects.filter(parent=r_id)
    if child_certs:
        helper = []
        for cert in child_certs:
            div_content = build_delete_item(cert)
            helper.append( mark_safe('Certificate: <a href="%s">%s</a> <img src="%spki/img/plus.png" class="switch" /><div class="details">%s</div>' % \
                                     (urlresolvers.reverse('admin:pki_certificate_change', args=(cert.pk,)), cert.name, MEDIA_URL, div_content)) )
            id_dict['cert'].append(cert.pk)
        store.append(helper)
    
    ## Search for related CA's
    child_cas = pki.models.CertificateAuthority.objects.filter(parent=r_id)
    if child_cas:
        helper = []
        for ca in child_cas:
            chain_recursion(ca.pk, helper, id_dict)
        store.append(helper)
Example #18
0
 def get_render_content(self, context):
     if self.nodelist:
         with context.push():
             context['content'] = self.get_content_from_context(context)
             output = self.nodelist.render(context)
         return mark_safe(output)
     return mark_safe(self.get_content_from_context(context))
Example #19
0
def render_fatpage(request, f):
    """
    Internal interface to the fat page view.
    """
    # If registration is required for accessing this page, and the user isn't
    # logged in, redirect to the login page.
    if f.registration_required and not request.user.is_authenticated():
        from django.contrib.auth.views import redirect_to_login
        return redirect_to_login(request.path)
    if f.template_name:
        t = loader.select_template((f.template_name, DEFAULT_TEMPLATE))
    else:
        t = loader.get_template(DEFAULT_TEMPLATE)

    # To avoid having to always use the "|safe" filter in fatpage templates,
    # mark the title and content as already safe (since they are raw HTML
    # content in the first place).
    f.title = mark_safe(f.title)
    f.content = mark_safe(f.content)

    c = RequestContext(request, {
        'fatpage': f,
    })
    response = HttpResponse(t.render(c))
    populate_xheaders(request, response, FatPage, f.id)
    return response
Example #20
0
    def test_reporting_of_nested_exceptions(self):
        request = self.rf.get('/test_view/')
        try:
            try:
                raise AttributeError(mark_safe('<p>Top level</p>'))
            except AttributeError as explicit:
                try:
                    raise ValueError(mark_safe('<p>Second exception</p>')) from explicit
                except ValueError:
                    raise IndexError(mark_safe('<p>Final exception</p>'))
        except Exception:
            # Custom exception handler, just pass it into ExceptionReporter
            exc_type, exc_value, tb = sys.exc_info()

        explicit_exc = 'The above exception ({0}) was the direct cause of the following exception:'
        implicit_exc = 'During handling of the above exception ({0}), another exception occurred:'

        reporter = ExceptionReporter(request, exc_type, exc_value, tb)
        html = reporter.get_traceback_html()
        # Both messages are twice on page -- one rendered as html,
        # one as plain text (for pastebin)
        self.assertEqual(2, html.count(explicit_exc.format('&lt;p&gt;Top level&lt;/p&gt;')))
        self.assertEqual(2, html.count(implicit_exc.format('&lt;p&gt;Second exception&lt;/p&gt;')))
        self.assertEqual(10, html.count('&lt;p&gt;Final exception&lt;/p&gt;'))

        text = reporter.get_traceback_text()
        self.assertIn(explicit_exc.format('<p>Top level</p>'), text)
        self.assertIn(implicit_exc.format('<p>Second exception</p>'), text)
        self.assertEqual(3, text.count('<p>Final exception</p>'))
Example #21
0
def candidate_office(c):
  """
  Usage:
  """
  ret = []

  state = c.state
  level = c.level
  office = c.office
  district = c.district

  try:
      if level == 'Federal':
          ret.append(office)
          ret.append(district)
      elif level == 'State':
          if office in ('Governor', 'Lt. Governor', 'Secretary of State'):
              ret.append(office)
          else:
              ret.append(level)
              ret.append(office)
              ret.append(district)
      elif level in Candidate.LEVEL_LIST:
          ret.append(office)
          ret.append(district)
      if not ret:
          log.error('Candidate %s: %s, %s, %s, %s', c, state, level, office,
                  district)
          ret.append('Unknown')
  except:
      raise
      log.error('Unknown error')
      pass

  return format_html('{} {}', mark_safe(state), mark_safe(' '.join(ret)))
def paginator_prev_page(cl):
    prevpage= cl.page_num -1 
    if prevpage <= -1:
        prevpage=0
        return mark_safe(u'<li class="active"><span>Prev</span></li>' )
    else:
        return mark_safe(u'<li><a href="%s">Prev</a></li> ' % (escape(cl.get_query_string({PAGE_VAR: prevpage}))))
Example #23
0
    def render(self, name, value, attrs=None):

        value = value or ''
        
        final_attrs = self.build_attrs(attrs)
        self.html_id = final_attrs.pop('id', name)

        lookup = get_lookup(self.channel)

        context = {
            'current_repr': mark_safe("'%s'" % escapejs(value)),
            'current_id': value,
            'help_text': self.help_text,
            'html_id': self.html_id,
            'min_length': getattr(lookup, 'min_length', 1),
            'lookup_url': reverse('ajax_lookup', args=[self.channel]),
            'name': name,
            'extra_attrs':mark_safe(flatatt(final_attrs)),
            'func_slug': self.html_id.replace("-",""),
        }
        context.update(bootstrap())

        templates = ('autocomplete_%s.html' % self.channel,
                     'autocomplete.html')
        return mark_safe(render_to_string(templates, context))
Example #24
0
def render_os(os):
    try:
        t, flavor = os.split("+", 1)
        flavor = " ".join(i.capitalize() for i in flavor.split("-"))
        return mark_safe("%s (<em>%s</em>)" % (flavor, t))
    except ValueError:
        return mark_safe(_("<em>Unknown or invalid OS</em>"))
Example #25
0
def get_query_string(p_list, p_dict, new_params, remove, context):
    """
    Add and remove query parameters. From `django.contrib.admin`.
    """
    for r in remove:
        p_list = [[x[0], x[1]] for x in p_list if not x[0].startswith(r)]
    for k, v in new_params.items():
        if k in p_dict and v is None:
            p_list = [[x[0], x[1]] for x in p_list if not x[0] == k]
        elif k in p_dict and v is not None:
            for i in range(0, len(p_list)):
                if p_list[i][0] == k:
                    p_list[i][1] = [v]

        elif v is not None:
            p_list.append([k, [v]])

    for i in range(0, len(p_list)):
        if len(p_list[i][1]) == 1:
            p_list[i][1] = p_list[i][1][0]
        else:
            p_list[i][1] = mark_safe('&amp;'.join([u'%s=%s' % (p_list[i][0], k) for k in p_list[i][1]]))
            p_list[i][0] = ''

        protected_keywords = ['block']
        if p_list[i][1] not in protected_keywords:
            try:
                p_list[i][1] = template.Variable(p_list[i][1]).resolve(context)
            except:
                pass

    return mark_safe('?' + '&amp;'.join([k[1] if k[0] == '' else u'%s=%s' % (k[0], k[1]) for k in p_list if k[1] is not None and k[1] != 'None']).replace(' ', '%20'))
    def _fetch_womi_params(self, request, womi_id, version):
        if version == 'none' or not self.use_version:
            version = None

        # TODO better way to obtain this path?
        womi_url = '/content/womi/%s/' % womi_id
        if self.use_version:
            womi_url += ('%s/' % version)

        full_domain = self.get_full_domain()
        with_schema_base_url = ('https:' if request.is_secure() else 'http:') + full_domain
        data = {'womi_url': womi_url,
                'base_url': with_schema_base_url}

        if self.use_dynamic:
            womi_content = mark_safe(self.get_dynamic_loader(womi_id, version))
        else:
            try:
                manifest_url = 'http:' + full_domain + womi_url + 'manifest.json'
                debug('fetching manifest %s', manifest_url)
                r = requests.get(manifest_url)
                r.raise_for_status()
                data.update(r.json())
                womi_content = resolve_womi(data)
            except ConnectionError as ce:
                womi_content = mark_safe(self.get_dynamic_loader(womi_id, version))

        return {
            'base_url': full_domain,
            'womi_id': womi_id,
            'version': version,
            'data': data,
            'womi_content': womi_content,
            'endpoints': self.endpoints
        }
def add_class(value, css_class):
    """
    http://stackoverflow.com/questions/4124220/django-adding-css-classes-when-rendering-form-fields-in-a-template

    Inserts classes into template variables that contain HTML tags,
    useful for modifying forms without needing to change the Form objects.

    Usage:

        {{ field.label_tag|add_class:"control-label" }}

    In the case of REST Framework, the filter is used to add Bootstrap-specific
    classes to the forms.
    """
    html = six.text_type(value)
    match = class_re.search(html)
    if match:
        m = re.search(r'^%s$|^%s\s|\s%s\s|\s%s$' % (css_class, css_class,
                                                    css_class, css_class),
                      match.group(1))
        if not m:
            return mark_safe(class_re.sub(match.group(1) + " " + css_class,
                                          html))
    else:
        return mark_safe(html.replace('>', ' class="%s">' % css_class, 1))
    return value
Example #28
0
def motion_details(request, days=3):
    devices = Device.objects.all()

    minutes = 10

    start = timezone.now() - timezone.timedelta(days=days)
    motion_time = []
    motion_count = []
    delta = timezone.timedelta(minutes=minutes)

    while start < timezone.now():
        cnt = Log.objects.filter(log_type__exact='MO', status=True, created__range=[start, start+delta]).count()
        motion_time.append(start)
        motion_count.append(cnt)

        start += delta
#    motion_datestmp = last_motion
    motion_time = mark_safe([timezone.localtime(m).strftime('%Y-%m-%d %H:%M:%S') for m in motion_time].__str__())
    #motion_state = mark_safe([ int(m.status) for m in last_motions].__str__())
    #motion_time = mark_safe(motion_time.__str__())
    motion_count = mark_safe(motion_count.__str__())

    range_start = mark_safe(timezone.localtime(timezone.now()-timezone.timedelta(days=1)).strftime('%Y-%m-%d %H:%M:%S'))
    range_end = mark_safe(timezone.localtime(timezone.now()).strftime('%Y-%m-%d %H:%M:%S'))

    return render_to_response(
        'motions.html',
        locals()
    )
    def render(self, name, value, attrs=None):
        widget_attrs = self.build_widget_attrs(name)

        autocomplete = self.autocomplete(values=value)

        attrs = self.build_attrs(attrs, autocomplete=autocomplete)

        self.html_id = attrs.pop('id', name)

        choices = autocomplete.choices_for_values()
        values = [autocomplete.choice_value(c) for c in choices]

        context = {
            'name': name,
            'values': values,
            'choices': choices,
            'widget': self,
            'attrs': safestring.mark_safe(flatatt(attrs)),
            'widget_attrs': safestring.mark_safe(flatatt(widget_attrs)),
            'autocomplete': autocomplete,
        }
        context.update(self.extra_context)

        template = getattr(autocomplete, 'widget_template',
                self.widget_template)
        return safestring.mark_safe(render_to_string(template, context))
Example #30
0
def header_for_result(result, headers):
    for i, td in enumerate(result):
        text = headers[i]['text']
        if not text.startswith('<'):
            yield mark_safe(td.replace('">', force_text('" data-label="%s : " >' % (text, ) )))
        else:
            yield mark_safe(td)