Example #1
0
def role(ctx, obj, role_name=None, **kwargs):
    """
    A filter that renders object according to the given role. In jinja, this
    is accomplished by ``obj|role('role name')``
    """
    try:
        request = ctx["request"]
    except KeyError:
        return html(obj, role_name, **kwargs)
    else:
        return html(obj, role_name, request=request, **kwargs)
Example #2
0
def render_collapsible(lst,
                       item_role='collapsible-item',
                       title=None,
                       expanded=False,
                       **kwargs):
    """
    Renders a queryset or list of objects

    Args:
        lst:
            List or queryset of objects inside the collapsible list.
        item_role:
            Role assigned to each element in the list. Defaults to
            'collapsible-item'.
        title (bool):
            Title in which the list of object is displayed.
        expanded (str):
            If true, start list in the "expanded" state.
    """
    if title is None:
        if isinstance(lst, QuerySet):
            title = title.model._meta.verbose_name_plural
        else:
            raise TypeError('must provide an explicit title!')

    data = [html(x, item_role, **kwargs) for x in lst]
    return div(class_='CollapsibleList', is_component=True)[
        h2([title, span(f'({len(data)})'
                        ), fa_icon('angle-up')]),
        div(class_='CollapsibleList-data')[html_list(data), ]]
Example #3
0
def render_collapsible(lst,
                       item_role='collapsible-item',
                       title=None,
                       expanded=False,
                       **kwargs):
    """
    Renders a queryset or list of objects

    Args:
        lst:
            List or queryset of objects inside the collapsible list.
        item_role:
            Role assigned to each element in the list. Defaults to
            'collapsible-item'.
        title (bool):
            Title in which the list of object is displayed.
        expanded (str):
            If true, start list in the "expanded" state.
    """
    if title is None:
        if isinstance(lst, QuerySet):
            title = title.model._meta.verbose_name_plural
        else:
            raise TypeError('must provide an explicit title!')

    data = [html(x, item_role, **kwargs) for x in lst]
    random_id = str(uuid.uuid4())
    display = 'block' if expanded else 'none'

    return div(
        class_='CollapsibleList'
    )[h2(onclick=f"$('#{random_id}').toggle()",
         children=[title, span(f'({len(data)})'),
                   fa_icon('angle-down')]),
      html_list(data, style=f'display: {display}', id=random_id), ]
Example #4
0
    def test_render_django_model(self, model_class):
        @html.register_template(model_class, 'example.html', role='simple')
        def renderer(obj):
            return {'obj': obj, 'answer': 42}

        obj = model_class()
        result = html(obj, 'simple')
        assert isinstance(result, Blob)
Example #5
0
def role_model_list(request, model, role):
    cls = get_class(model)
    kwargs = query_to_kwargs(request)
    size = kwargs.pop("size", 10)
    data = []
    for idx, obj in enumerate(cls.objects.all()[:size], 1):
        link = reverse("role-model-instance", kwargs={"model": model, "role": role, "id": obj.id})
        key = span([f"{idx}) ", a(str(obj), href=link)])
        data.append((key, html(obj, role, **kwargs)))

    return {"data": html_map(data)}
Example #6
0
def role_model_list(request, model, role):
    cls = get_class(model)
    kwargs = query_to_kwargs(request)
    size = kwargs.pop('size', 10)
    data = []
    for idx, obj in enumerate(cls.objects.all()[:size], 1):
        link = reverse('role-model-instance',
                       kwargs={'model': model, 'role': role, 'id': obj.id})
        key = span([f'{idx}) ', a(str(obj), href=link)])
        data.append((key, html(obj, role, **kwargs)))

    return {'data': html_map(data)}
Example #7
0
    def render_queryset(qs, role=None, **kwargs):
        """
        Renders a queryset object. Dispatch by role and model.
        """
        model = qs.model
        key = (model, role)
        if role:
            kwargs['role'] = role

        try:
            renderer = registry[key]
        except KeyError:
            return html_list(html(x, **kwargs) for x in qs)
        else:
            return renderer(qs, **kwargs)
Example #8
0
def comment_card(comment: Comment,
                 request=None,
                 target=None,
                 show_actions=None,
                 **kwargs):
    """
    Render comment information inside a comment card.
    """

    user = getattr(request, "user", None)
    is_authenticated = getattr(user, "is_authenticated", False)

    if is_authenticated:
        login_anchor = None
    else:
        login = reverse("auth:login")
        login_anchor = a(
            _("login"),
            href=f"{login}?next={comment.conversation.get_absolute_url()}")

    badge = ""
    if HAS_GAMIFICATION:
        from ej_gamification import get_participation

        level = get_participation(user, comment.conversation).voter_level
        badge = html(level, role="stars")

    buttons = {
        "disagree": ("fa-times", "text-negative", _("Disagree")),
        "skip": ("fa-arrow-right", "text-black", _("Skip")),
        "agree": ("fa-check", "text-positive", _("Agree")),
    }

    return {
        "author": comment.author.username,
        "comment": comment,
        "show_actions": is_authenticated,
        "csrf_input": csrf_input(request),
        "buttons": buttons,
        "login_anchor": login_anchor,
        "target": target,
        "badge": badge,
        **kwargs,
    }
Example #9
0
def collapsible_list(lst, item_role="list-item", title=None, **kwargs):
    """
    Renders a queryset or list of objects

    Args:
        lst:
            List or queryset of objects inside the collapsible list.
        item_role:
            Role assigned to each element in the list. Defaults to
            'list-item'.
        title (bool):
            Title in which the list of object is displayed.
        expanded (str):
            If true, start list in the "expanded" state.
    """
    size = len(lst)
    title = _title(lst) if title is None else title
    title = Block([title, span(f" ({size})", class_="text-accent")])
    items = [html(x, item_role, **kwargs) for x in lst]
    data = html_list(items, class_="list-reset")
    return collapsible(data, title=title)
Example #10
0
def role_queryset(request, model, role):
    cls = get_class(model)
    qs = cls.objects.all()
    kwargs = query_to_kwargs(request)
    size = kwargs.pop("size", 10)
    return {"data": html(qs[:size], role, **kwargs)}
Example #11
0
def role_model_instance(request, model, role, id):
    cls = get_class(model)
    obj = cls.objects.get(id=id)
    kwargs = query_to_kwargs(request)
    return {"data": html(obj, role, **kwargs)}
Example #12
0
def _render_lazy_string(st, **kwargs):
    return html(str(st))
Example #13
0
def non_strict_render(obj, role=None, ctx=None, strict=False):
    return html(obj, role=role, ctx=ctx, strict=strict)
Example #14
0
 def test_cannot_render_wrong_role(self):
     with pytest.raises(TypeError):
         html('foo', 'bad-role')
Example #15
0
    def test_role_dispatch(self):
        assert html.dispatch(int)(42) == html(42)

        with pytest.raises(TypeError):
            print(html.dispatch(int, 'foo')(42))