Source code for bricks.helpers.hyperlink

import collections
from html import escape

from .attr import attrs as _attrs
from .escape import safe, Markup
from ..utils import lazy_singledispatch


@lazy_singledispatch



@hyperlink.register(Markup)
def _hyperlink_markup(x, href=None, attrs=None, **kwargs):
    if href is None:
        x, href = parse_link(x)
    if href:
        kwargs['href'] = href
    attrs_string = _attrs(attrs, **kwargs)
    if attrs_string:
        attrs_string = ' ' + attrs_string
    return safe('<a%s>%s</a>' % (attrs_string, x))


@hyperlink.register(str)
def _(x, href=None, attrs=None, **kwargs):
    if href is None:
        x, href = parse_link(x)
    return _hyperlink_markup(escape(x), href, attrs, **kwargs)


@hyperlink.register(collections.Mapping)
def _(x, href=None, attrs=None, **kwargs):
    data = dict(x)
    content = data.pop('content', '')
    if attrs:
        data.update(attrs)
    attrs_string = _attrs(data, **kwargs)
    if attrs_string:
        attrs_string = ' ' + attrs_string
    return safe('<a%s>%s</a>' % (attrs_string, content))


@hyperlink.register('django.db.models.Model')
def _(x):
    return safe('<a href="%s">%s</a>' % (x.get_absolute_url(), x))


def parse_link(name):
    """
    Return a tuple with (name, link) from a string of "name<link>".

    If no link is found, the second value is None.
    """

    if name.endswith('>'):
        name, sep, link = name.partition('<')
        if sep:
            return name, link[:-1]
    return name, None