Python django.utils.html 模块,mark_safe() 实例源码

我们从Python开源项目中,提取了以下50个代码示例,用于说明如何使用django.utils.html.mark_safe()

项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def render_plugins(context, plugins):
    """
    Render a list of plugins. Requires the
    :class:`feincms3.renderer.TemplatePluginRenderer` instance in the context
    as ``renderer``::

        {% render_plugins plugins %}

    This plugin is equivalent to::

        {% for plugin in plugins %}{% render_plugin plugin %}{% endfor %}

    In general you should prefer
    :func:`~feincms3.templatetags.feincms3_renderer.render_region` over this
    tag.
    """
    renderer = context['renderer']
    return mark_safe(''.join(
        renderer.render_plugin_in_context(plugin, context)
        for plugin in plugins
    ))
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def indented_title(self, instance):
        """
        Use Unicode box-drawing characters to visualize the tree hierarchy.
        """
        box_drawing = []
        for i in range(instance.depth - 2):
            box_drawing.append('<i class="l"></i>')
        if instance.depth > 1:
            box_drawing.append('<i class="a"></i>')

        return format_html(
            '<div class="box">'
            '<div class="box-drawing">{}</div>'
            '<div class="box-text" style="text-indent:{}px">{}</div>'
            '</div>',
            mark_safe(''.join(box_drawing)),
            (instance.depth - 1) * 30,
            instance,
        )
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def render(self, region, context, timeout=None):
        """render(self, region, context, *, timeout=None)
        Render a single region using the context passed

        If ``timeout`` is ``None`` caching is disabled.

        .. note::
           You should treat anything except for the ``region`` and ``context``
           argument as keyword-only.
        """
        if timeout is not None:
            key = self.cache_key(region)
            html = cache.get(key)
            if html is not None:
                return html

        html = mark_safe(''.join(
            self._renderer.render_plugin_in_context(plugin, context)
            for plugin in self._contents[region]
        ))

        if timeout is not None:
            cache.set(key, html, timeout=timeout)
        return html
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def kolibri_language_globals(context):
    lang_dir = "rtl" if get_language_bidi() else "ltr"
    js = """
    <script>
      var languageCode = '{lang_code}';
      var languageDir = '{lang_dir}';
      var languages = JSON.parse('{languages}');
    </script>
    """.format(
        lang_code=get_language(),
        lang_dir=lang_dir,
        languages=json.dumps({code: {
            # Format to match the schema of the content Language model
            'id': code,
            'lang_name': name,
            'lang_direction': get_language_info(code)['bidi']
        } for code, name in settings.LANGUAGES}),
    )
    return mark_safe(js)
项目:eventroller    作者:MoveOnOrg    | 项目源码 | 文件源码
def get_extra_event_management_html(self, event):
        if event.source_json_data:
            json_data = json.loads(event.source_json_data)
            hosts = json_data.get('hosts')
            additional_hosts = []
            if hosts:
                for hostpk, host in hosts.items():
                    if int(hostpk) not in self.ignore_hosts\
                       and (not event.organization_host_id\
                            or hostpk != event.organization_host.member_system_pk):
                        additional_hosts.append(host)
                if additional_hosts:
                    return mark_safe(
                        '<div><b>Additional Hosts:</b>'
                        + ''.join([
                            format_html('<span data-pk="{}">{}</span>', h['member_system_pk'], h['name'])
                            for h in additional_hosts])
                        + '</div>')
        return None
项目:directory-ui-supplier    作者:uktrade    | 项目源码 | 文件源码
def get_results_from_search_response(response):
    parsed = response.json()
    formatted_results = []

    for result in parsed['hits']['hits']:
        formatted = format_company_details(result['_source'])
        if 'highlight' in result:
            highlighted = '...'.join(
                result['highlight'].get('description', '') or
                result['highlight'].get('summary', '')
            )
            # escape all html tags other than <em> and </em>
            highlighted_escaped = (
                escape(highlighted)
                .replace('&lt;em&gt;', '<em>')
                .replace('&lt;/em&gt;', '</em>')
            )
            formatted['highlight'] = mark_safe(highlighted_escaped)
        formatted_results.append(formatted)

    parsed['results'] = formatted_results
    return parsed
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
def field_choices(self, field, request, model_admin):
        mptt_level_indent = getattr(model_admin, 'mptt_level_indent', self.mptt_level_indent)
        language_bidi = get_language_bidi()
        initial_choices = field.get_choices(include_blank=False)
        pks = [pk for pk, val in initial_choices]
        models = field.related_model._default_manager.filter(pk__in=pks)
        levels_dict = {model.pk: getattr(model, model._mptt_meta.level_attr) for model in models}
        choices = []
        for pk, val in initial_choices:
            padding_style = ' style="padding-%s:%spx"' % (
                'right' if language_bidi else 'left',
                mptt_level_indent * levels_dict[pk])
            choices.append((pk, val, mark_safe(padding_style)))
        return choices

    # Ripped from contrib.admin.filters,RelatedFieldListFilter Django 1.8 to
    # yield padding_style
项目:api-django    作者:lafranceinsoumise    | 项目源码 | 文件源码
def html_full_contact(self):
        parts = []

        if self.contact_name and self.contact_email:
            parts.append(format_html(
                '{name} &lt;<a href="mailto:{email}">{email}</a>&gt;',
                name=self.contact_name,
                email=self.contact_email
            ))
        elif self.contact_name:
            parts.append(self.contact_name)
        elif self.contact_email:
            parts.append(format_html('<a href="mailto:{email}">{email}</a>', email=self.contact_email))

        if self.contact_phone and not self.contact_hide_phone:
            parts.append(self.contact_phone)

        if parts:
            return format_html_join(mark_safe(" &mdash; "), '{}', ((part,) for part in parts))
        else:
            return format_html("<em>{}</em>", _("Pas d'informations de contact"))
项目:django-functest    作者:django-functest    | 项目源码 | 文件源码
def as_p(self):
        retval = super(AddSpacersMixin, self).as_p()
        if self.add_spacers:
            # Hack to help test interacting with elements
            # that aren't in view.
            retval = mark_safe(retval.replace('</p>', '</p>' + ('<br>' * 100)))
        return retval
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def indent(self, depth):
        return mark_safe('&#x251c;' * (depth - 1))
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def register_string_renderer(self, plugin, renderer):
        """
        Register a rendering function which is passed the plugin instance and
        returns a HTML string::

            renderer.register_string_renderer(
                RichText,
                lambda plugin: mark_safe(plugin.text),
            )
        """
        self._renderers[plugin] = (None, renderer)
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def render_html(plugin, **kwargs):
    """
    Return the HTML code as safe string so that it is not escaped. Of course
    the contents are not guaranteed to be safe at all
    """
    return mark_safe(plugin.html)
项目:feincms3    作者:matthiask    | 项目源码 | 文件源码
def render_richtext(plugin, **kwargs):
    """
    Return the text of the rich text plugin as a safe string (``mark_safe``)
    """
    return mark_safe(plugin.text)
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def dict_to_json(pydict):
    """
    Accepts a python dict and returns it's JSON representation.

    Sample usage::

        <script type="application/ld+json">
            {% dict_to_json some_dict %}
        </script>
    """
    return mark_safe(json.dumps(pydict))
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def inline_static_file(path, minify=None):
    """
    Outputs the [minified] contents of a given static file.

    For example, to display the minified CSS file "``inline.css``"::

        <style>
            {% inline_static_file 'inline.css' 'css' %}
        </style>

    The optional ``minify`` argument can be one of css, js, or html.
    """
    p = finders.find(path)

    if not p:
        raise RuntimeError('path=%s not found' % path)
    elif os.path.isdir(p):
        raise RuntimeError('path=%s is not a file' % path)

    with open(p, encoding='utf-8') as f:
        if minify == 'js':
            return mark_safe(js_minify(f.read()))
        elif minify == 'css':
            return mark_safe(css_minify(f.read()))
        elif minify == 'html':
            return mark_safe(html_minify(f.read()))
        else:
            return mark_safe(f.read())
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def autofocus_form(form, *args, **kwargs):
    """
    Add the 'autofocus' attribute to the first input tag of a form.

    Usage::

        {% autofocus_form form form_group_class='row' %}

    Extra args and kwargs are passed to ``bootstrap_form``.
    """
    return mark_safe(re.sub(
        '<input', '<input autofocus',
        str(bootstrap_form(form, *args, **kwargs)),
        count=1
    ))
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def autofocus_field(field, *args, **kwargs):
    """
    Add the 'autofocus' attribute to an input tag.

    Usage::

        {% autofocus_field field field_class='col-md-12' %}

    Extra args and kwargs are passed to ``bootstrap_field``.
    """
    return mark_safe(re.sub(
        '<input', '<input autofocus',
        str(bootstrap_field(field, *args, **kwargs)),
        count=1
    ))
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def minify_js(value):
    return mark_safe(js_minify(value))
项目:site    作者:alphageek-xyz    | 项目源码 | 文件源码
def minify_html(value):
    return mark_safe(html_minify(value))
项目:django-croppie    作者:dima-kov    | 项目源码 | 文件源码
def make_script_vars(self, name):
        context = self.process_croppie_context(name)
        vars = 'var croppieFieldName = "{}"\n var croppieOptions = {}' \
            .format(
                context['croppie_field_name'],
                context['croppie_options'],
            )
        return mark_safe(vars)
项目:wagtailhallosample    作者:didorothy    | 项目源码 | 文件源码
def editor_css():
    return mark_safe(
    '''
    <style>
    .highlight-red { background: red; color: white; }
    .highlight-yellow { background: yellow; color: black; }
    .highlight-red { background: gray; color: red; }
    </style>
    ''')
项目:PonyConf    作者:PonyConf    | 项目源码 | 文件源码
def markdown_to_html(md):
    html = markdown(md)
    allowed_tags = bleach.ALLOWED_TAGS + ['p', 'pre', 'span' ] + ['h%d' % i for i in range(1, 7) ]
    html = bleach.clean(html, tags=allowed_tags)
    return mark_safe(html)
项目:sdining    作者:Lurance    | 项目源码 | 文件源码
def render(self, data, accepted_media_type=None, renderer_context=None):
        codec = coreapi.codecs.CoreJSONCodec()
        schema = base64.b64encode(codec.encode(data))

        template = loader.get_template(self.template)
        context = {'schema': mark_safe(schema)}
        request = renderer_context['request']
        return template_render(template, context, request=request)
项目:silica    作者:zagaran    | 项目源码 | 文件源码
def angular_model(model, angular_model_name, extra_params={}):
    """ Returns javascript that preprocesses obj before attaching it to window
        where angular controller can grab it """
    ret = "<script>\n"
    if model is None:
        ret += "window.%s = {};\n" % (angular_model_name)
    else:
        # cast foreign key and m2m fields to be strings
        json_ret = model.to_json()
        model_dict = json.loads(json_ret)
        fk_fields = model.get_foreign_key_fields()
        m2m_fields = model.get_many_to_many_fields()
        for field, val in model_dict["fields"].iteritems():
            if field in fk_fields:
                model_dict["fields"][field] = str(val)
            if field in m2m_fields:
                model_dict["fields"][field] = map(str, val)
        ret += "window.%s = %s;\n" % (angular_model_name, json.dumps(model_dict, sort_keys=True))
        # adds converter for datetime fields
        for field in model.READABLE_ATTRS(type_filter=models.DateField):
            # DateTimeFields are instances of DateFields
            ret += ("window.%s.fields.%s = new Date(window.%s.fields.%s);\n" %
                    (angular_model_name, field, angular_model_name, field))
    # date_fields = model.WRITEABLE_ATTRS(type_filter=models.DateField, type_exclude=models.DateTimeField)
    # date_fields = json.dumps(date_fields)
    # ret += "window.%s.date_fields = %s" % (angular_model_name, date_fields)
    ret += "</script>\n"
    return mark_safe(ret)
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def to_json(data):
    return mark_safe(JSONRenderer().render(data).decode('utf-8'))
项目:intake    作者:codeforamerica    | 项目源码 | 文件源码
def contact_info_to_html(contact_info_dict):
    phone = contact_info_dict.get('sms', '')
    if phone:
        phone = format_phone_number(phone)
    email = contact_info_dict.get('email', '')

    html = oxford_comma([
        thing for thing in (phone, email) if thing])
    return mark_safe(html)
项目:multiuploader    作者:vinaypost    | 项目源码 | 文件源码
def render(self, name, value, attrs=None, choices=()):
        widget_ = super(MultiuploadWidget, self).render(name, value, attrs)
        output = '<div id="hidden_container" style="display:none;">%s</div>' % widget_
        return mark_safe(output)
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def kolibri_main_navigation():
    """
    A tag to include an initial JS-object to bootstrap data into the app.
    :return: An html string
    """
    init_data = {
        'nav_items': [],
        'user_nav_items': [],
    }

    for hook in NavigationHook().registered_hooks:
        init_data['nav_items'].append({
            'text': str(hook.label),
            'url': str(hook.url),
        })

    for hook in UserNavigationHook().registered_hooks:
        init_data['user_nav_items'].append({
            'text': str(hook.label),
            'url': str(hook.url),
        })

    html = ("<script type='text/javascript'>"
            "window._nav={0};"
            "</script>".format(json.dumps(init_data)))
    return mark_safe(html)
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def kolibri_set_urls(context):
    js_global_object_name = getattr(settings, 'JS_REVERSE_JS_GLOBAL_OBJECT_NAME', JS_GLOBAL_OBJECT_NAME)
    js_var_name = getattr(settings, 'JS_REVERSE_JS_VAR_NAME', JS_VAR_NAME)
    js = (js_reverse_inline(context) +
          "Object.assign({0}.urls, {1}.{2})".format(settings.KOLIBRI_CORE_JS_NAME,
                                                    js_global_object_name,
                                                    js_var_name))
    return mark_safe(js)
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def kolibri_set_server_time():
    html = ("<script type='text/javascript'>"
            "{0}.utils.serverClock.setServerTime({1});"
            "</script>".format(settings.KOLIBRI_CORE_JS_NAME,
                               json.dumps(now(), cls=DjangoJSONEncoder)))
    return mark_safe(html)
项目:kolibri    作者:learningequality    | 项目源码 | 文件源码
def kolibri_bootstrap_model(context, base_name, api_resource, **kwargs):
    response, kwargs, url_params = _kolibri_bootstrap_helper(context, base_name, api_resource, 'detail', **kwargs)
    html = ("<script type='text/javascript'>"
            "var model = {0}.resources.{1}.createModel(JSON.parse({2}), {3});"
            "model.synced = true;"
            "</script>".format(settings.KOLIBRI_CORE_JS_NAME,
                               api_resource,
                               json.dumps(JSONRenderer().render(response.data).decode('utf-8')),
                               json.dumps(url_params)))
    return mark_safe(html)
项目:django-experience    作者:rg3915    | 项目源码 | 文件源码
def active_tag(context):
    if context:
        span = 'glyphicon-ok-sign green'
    else:
        span = 'glyphicon-minus-sign red'
    return mark_safe('<span class="glyphicon {}"></span>'.format(span))
项目:django_kbbi    作者:efenfauzi    | 项目源码 | 文件源码
def arti_kata(self, obj):
        return mark_safe(obj.artikata)
项目:osedev    作者:damoti    | 项目源码 | 文件源码
def embed_graph(context, period, graph, username=None):
    request = context['request']
    kwargs = {'period': period, 'graph': graph}
    if username is not None:
        kwargs['username'] = username
    url = "{}://{}{}".format(
        request.scheme, request.get_host(), reverse('graph.embed', kwargs=kwargs)
    )
    iframe = escape('<html><iframe width="600" height="350" src="{}"></iframe></html>'.format(url))
    return mark_safe('<code>'+iframe+'</code>')
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def iconImage(self):
        return format_html('<img src="/{}"/>', mark_safe(self.icon))
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def iconImageSmall(self):
        return format_html('<img height="30" width="30" src="/{}"/>', mark_safe(self.icon))
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def iconImage(self):
        return format_html('<img height="30" src="/{}"/>', mark_safe(self.icon))
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def iconImageSmall(self):
        return format_html('<img height="15" width="45" src="/{}"/>', mark_safe(self.file))
项目:Tethys    作者:JosePedroMatos    | 项目源码 | 文件源码
def pRovider(self, instance):
        return format_html('<img height="30" src="/{}"/> ({})', mark_safe(instance.provider.icon), mark_safe(instance.provider.abbreviation))
项目:eventroller    作者:MoveOnOrg    | 项目源码 | 文件源码
def host_format(event):
    host = event.organization_host
    host_line = [format_html('{}', host)]
    host_items = []
    if event.host_is_confirmed:
        host_line.append(mark_safe(' (<span style="color:green">confirmed</span>) '))
    else:
        host_line.append(mark_safe(' (<span style="color:red">unconfirmed</span>) '))

    host_line.append(mark_safe('<br />'))

    if getattr(host, 'email', None):
        host_items.append(format_html('<a data-system-pk="{}" href="mailto:{}">email</a>',
                                      host.member_system_pk or '',
                                      host.email,
                                      host))


    host_link = event.host_edit_url(edit_access=True)
    if host_link:
        host_items.append(format_html('<a href="{}">Act as host</a>', host_link))
        if getattr(host, 'email', None) and getattr(settings, 'FROM_EMAIL', None):
            host_items.append(message_to_host(event))

    # from the connector
    extra_html=event.extra_management_html()
    if extra_html:
        host_items.append(extra_html)

    # give settings a chance to tweak/alter/add items
    customize_host_link = getattr(settings, 'EVENT_REVIEW_CUSTOM_HOST_DISPLAY', None)
    if callable(customize_host_link):
        host_items = customize_host_link(event, host_items)
    host_items.insert(0, ' '.join(host_line))
    return mark_safe(' <span class="glyphicon glyphicon-star-empty"></span>'.join(host_items))
项目:django-twilio-tfa    作者:rtindru    | 项目源码 | 文件源码
def media_js(self, request):
        # NOTE: Avoid loading models at top due to registry boot...
        from allauth.socialaccount.models import SocialApp

        locale = self.get_locale_for_request(request)
        try:
            app = self.get_app(request)
        except SocialApp.DoesNotExist:
            raise ImproperlyConfigured("No Facebook app configured: please"
                                       " add a SocialApp using the Django"
                                       " admin")

        def abs_uri(name):
            return request.build_absolute_uri(reverse(name))

        fb_data = {
            "appId": app.client_id,
            "version": GRAPH_API_VERSION,
            "locale": locale,
            "loginOptions": self.get_fb_login_options(request),
            "loginByTokenUrl": abs_uri('facebook_login_by_token'),
            "cancelUrl": abs_uri('socialaccount_login_cancelled'),
            "logoutUrl": abs_uri('account_logout'),
            "loginUrl": request.build_absolute_uri(self.get_login_url(
                request,
                method='oauth2')),
            "errorUrl": abs_uri('socialaccount_login_error'),
            "csrfToken": get_token(request)
        }
        ctx = {'fb_data': mark_safe(json.dumps(fb_data))}
        return render_to_string('facebook/fbconnect.html', ctx,
                                request=request)
项目:directory-ui-supplier    作者:uktrade    | 项目源码 | 文件源码
def render(self, name, value, attrs=None):
        input_html = super().render(name, value, attrs)
        wrapper_html = self.template.format(
            input_html=input_html, label=self.label, id=attrs['id']
        )
        return mark_safe(wrapper_html)
项目:hydra    作者:Our-Revolution    | 项目源码 | 文件源码
def render(self):
        id_ = self.attrs.get('id')
        output = []
        descriptions = dict(Slack.objects.values_list('id', 'description'))
        for i, choice in enumerate(self.choices):
            choice_value, choice_label = choice
            w = self.choice_input_class(self.name, self.value, self.attrs.copy(), choice, i)
            output.append(format_html(self.inner_html, choice_value=force_text(w), sub_widgets=mark_safe(format_html('<p>{}</p>', descriptions[choice_value]))))
        return format_html(
            self.outer_html,
            id_attr=format_html(' id="{}"', id_) if id_ else '',
            content=mark_safe('\n'.join(output)),
        )
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
def _get_level_indicator(self, obj):
        level = getattr(obj, obj._mptt_meta.level_attr)
        return mark_safe(conditional_escape(self.level_indicator) * level)
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
def label_from_instance(self, obj):
        """
        Creates labels which represent the tree level of each node when
        generating option labels.
        """
        level_indicator = self._get_level_indicator(obj)
        return mark_safe(level_indicator + ' ' + conditional_escape(smart_text(obj)))
项目:gougo    作者:amaozhao    | 项目源码 | 文件源码
def __html__(self):
        return format_html(
            '{}"{}',
            static(self.js),
            mark_safe(flatatt(self.attrs)),
        ).rstrip('"')
项目:django-tips    作者:trojsten    | 项目源码 | 文件源码
def rendered_text(self):
        return mark_safe(markdown(self.text, **getattr(
            settings, 'TIPS_MARKDOWN_KWARGS', {}
        )))
项目:django-billometer    作者:tcpcloud    | 项目源码 | 文件源码
def get_links(self, instance):
        links = []
        links.append('<a href="/v1/server-list/%s/">Server API</a>' %
                     instance.openstack_tenant)
        links.append('<a href="/v1/quota-sync/%s/">Sync Quotas</a>' %
                     instance.openstack_tenant)
        return mark_safe(' | '.join(links))
项目:serveradmin    作者:innogames    | 项目源码 | 文件源码
def _prepare_regexp_html(regexp):
    """Return HTML for a given regexp. Includes wordbreaks."""
    if not regexp:
        return ''
    else:
        regexp_html = (escape_html(regexp).replace('|', '|&#8203;')
                       .replace(']', ']&#8203;').replace(')', ')&#8203;'))
        return mark_safe(regexp_html)
项目:django-controlcenter    作者:byashimov    | 项目源码 | 文件源码
def jsonify(obj):
    return mark_safe(json.dumps(obj, cls=DjangoJSONEncoder))